简体   繁体   中英

R add legend to ggplot2

I want to plot several densities, where the legend should reveal the parameters for each density function. Unfortunately, ggplot2 does not include the legend (which is weird, in the tutorial it did...)

Generate data:

x <- seq(from=-5, to=5, by=0.1)
y1 = dlaplace(x,0,0.5)
y2 = dlaplace(x,0,1)
y3 = dlaplace(x,0,2)
df = data.frame(x,y1,y2,y3)

Plot

ggplot(data=df, aes(x=x))+
  geom_line(data= df, aes(y=y1), color="red")+
  geom_line(data= df,aes(y=y2), color="blue")+
  geom_line(data= df,aes(y=y3), color="green")+
  ggtitle("Gamma distribution density function") +ylab("density")+ xlab("x")+
  theme(legend.position = "bottom")+
  guides(fill = guide_legend(reverse=TRUE))

I am new to ggplot , and the following threads seemed related but unfortunately did not help me solve it ( here and here )

As Markus suggested, you'll need to convert your data to long format by meting it. Use melt function from reshape2 . It should look something like this:

plotdf <- as.data.frame(t(df))
plotdf$var <- rownames(plotdf)
plotdf <- melt(plotdf[-c(1),], id.vars = "var")
print(ggplot(plotdf, aes(value, variable, colour = var)) + geom_point()+ scale_y_discrete(breaks=seq(0, 2, by = 0.5)) +
      ggtitle("Gamma distribution density function") +ylab("density")+ xlab("x")+
        theme(legend.position = "bottom")+
        guides(fill = guide_legend(reverse=TRUE)))

Output:

这是输出图

Can format the plot more using other ggplot features. Check this: How to melt R data.frame and plot group by bar plot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM