rggplot2graphdensity-plot

Density Plot of Year and Value


I simply cannot get a density plot for the following data set:

A single y Varibale and corresponding year

I have tried copying code and simply modifying and i simply can't get it to work.

I need to look like below:

Density Plot

I need the X -axis to be years and the y- axis to be in millions.

Any help would be greatly appreciated.

Code:

library(ggplot2)
library(ggthemes)
library(tidyverse)


ggplot(data = density, aes(x = welfare)) +
  geom_density(fill = 'steelblue', color = 'black') +
  theme_economist()

Solution

  • Here is a suggestion, how we could do it:

    library(tidyverse)
    library(ggthemes)
    library(lubridate)
    library(scales)
    df %>% 
      mutate(welfare_num = parse_number(welfare)) %>%
      mutate(year = ymd(paste(year, 1, 1, sep="-"))) %>% 
      ggplot(aes(x = year, y = welfare_num)) +
      geom_area(fill = "#63CB99", color = "#63CB99", alpha = 0.5) +
      scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
      scale_y_continuous(labels = dollar_format(prefix = "$", big.mark = ",")) +
      theme_economist()+
      labs(x = "YEAR", y="WELFARE")
    
    

    data:

    df <- structure(list(year = 2013:2022, welfare = c("$388,866,936.62", 
    "$726,076,253.19", "$1,266,141,639.47", "$987,167,047.54", "$1,392,749,702.19", 
    "$1,335,220,815.50", "$1,819,630,833.96", "$2,359,170,587.39", 
    "$3,283,576,817.91", "$3,668,277,476.93")), class = "data.frame", row.names = c(NA, 
    -10L))
    

    enter image description here