safex
safex

Reputation: 2514

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)

Upvotes: 0

Views: 61

Answers (1)

snair.stack
snair.stack

Reputation: 415

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:

Here's the output plot

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

Upvotes: 1

Related Questions