Home > other >  What function can plot the distribution on the Y axis of line chart in R?
What function can plot the distribution on the Y axis of line chart in R?

Time:02-01

Please tell me in R, what function or package can plot the distribution of time series data on the Y axis of a line chart.

Such as the graphs below.

Example

Thank you for your any help.

CodePudding user response:

You can do this using ggplot2 and patchwork.

Start by loading the libraries:

library(ggplot2)
library(patchwork)

Now let's create some sample data to use:

df <- airquality
df$Date <- seq(from = as.Date("1973-05-01"), 
               to   = as.Date("1973-09-30"), 
               by   = "1 day")

We can make the density plot like this

p1 <- ggplot(df, aes(y = Temp))  
  geom_density(fill = "blue", alpha = 0.2, color = "blue")  
  theme_classic()  
  theme(axis.ticks.x = element_line(color = "white"),
        axis.text.x = element_text(color = "white"),
        axis.title.x = element_text(color = "white"),
        axis.line.x = element_line(color = "white")
        )

And the main time series plot like this:

p2 <- ggplot(df, aes(Date, Temp))  
  geom_line(color = "blue")  
  theme_classic()  
  theme(panel.background = element_rect(fill = "#fef8d6"),
        axis.ticks.length.y = unit(0, "pt"),
        axis.text.y = element_blank(),
        axis.title.y = element_blank())

To draw them we can do:

p1   p2   plot_layout(widths = c(1, 8))

enter image description here

  •  Tags:  
  • Related