Home > Software design >  How to change items in a ggplot2 legend?
How to change items in a ggplot2 legend?

Time:07-03

I am trying to change the legend items of this plot.

My code is:

library(ggplot2)
library(HDInterval)
library(ggridges)

df <- data.frame(
  density = c(rgamma(400, 2, 10), rgamma(400, 2.25, 9), rgamma(400, 5, 7)),
  source = rep(c("source_1", "source_2", "source_3"),
               each = 400))

ggplot(df, aes(x = density, color = source, linetype = source,
                                fill = after_stat(ifelse(quantile == 2, NA, color))))  
  geom_density_ridges_gradient(aes(y = 0), quantile_lines = TRUE, size=1.2, 
                               quantile_fun = hdi, # vline_linetype = 0, scale = 1)  
  labs(y = "Density", x = "Contribution")   
  
 scale_linetype_cyclical(name = "Source", values = c("solid", "dotted", "longdash"),
                          labels = c("source1", "source2", "source3"),
                          guide = "legend")  
  
  scale_fill_cyclical(name = "Source", values = c("#31a354", "#2c7fb8", "#d95f0e"),
                      labels = c("source1", "source2", "source3"),
                      guide = "none", na.value = "transparent")  
  
  scale_color_cyclical(name = "Source", values = c("#31a354", "#2c7fb8", "#d95f0e"),
                       labels = c("source1", "source2", "source3"),
                       guide = "none")  

  ylim(0, 8)   xlim(0, 1)  
  theme(#legend.position=c(.85,.75),
    legend.text = element_text(size=16), # item legend text font size
    legend.title=element_text(size=18), # title font size
    legend.key.height= unit(1, 'cm'),# box height
    legend.key.width= unit(1, 'cm'))    # box width
  guides(color = guide_legend(override.aes = list(fill = "white"))) 
  theme(axis.text.y  = element_text(size = 12, vjust = 0.5),
        axis.text.x  = element_text(size = 12, vjust = 0.5),  
        axis.title.x = element_text(size = 14),
        axis.title.y = element_text(size = 14))

I would like to show lines in the legend, instead of the boxes.

enter image description here

I would appreciate your help.
I have tried to understand ggridges deeply, however it is a bit different or rigid for some things.
Thanks in advance.

CodePudding user response:

ggplot(df, aes(x = density, color = source, linetype = source,
               fill = after_stat(ifelse(quantile == 2, NA, color))))  
  geom_density_ridges_gradient(aes(y = 0), size=1.2, 
                               quantile_lines = TRUE, quantile_fun = hdi,
                               key_glyph = "path")  
  ...

enter image description here

  • Related