简体   繁体   中英

Custom legend with ggplot2 in R having multiple density plots

I'm trying to add a legend to my plot, and here's what I have for now:

require(ggplot2)
d1 = data.frame(rnorm(100, mean=5))
d2 = data.frame(rnorm(50, mean=7))
single_data = 5.5
max_y = max(max(density(d1[,1])$y), max(density(d2[,1])$y))
print(ggplot() + geom_density(aes(x=d1), colour='black', data=d1, kernel='gaussian', alpha=.1, fill='red') + 
        geom_density(aes(x=d2), colour="black", data=d2, kernel='gaussian', alpha=.1, fill='blue') + 
        geom_segment(aes(x=single_data, xend=single_data, y=0, yend=max_y), colour='blue') +
        xlab("Count") + ylab("Density") + ggtitle('Main Title') +
        theme(legend.position='right') +
        scale_color_manual(name = "Data",
                           labels = c(5, 7),
                           values = c('red', 'blue'))
)

I expect to see a legend on the right side of the plot, but here's the output:

代码样本输出

How can I add a legend for these two density plots?

Here's the code that can come pretty close. You can fiddle with the rest.

library(ggplot2)
set.seed(9)
d1 = data.frame(d1 = rnorm(100, mean=5))
d2 = data.frame(d2 = rnorm(50, mean=7))
single_data = 5.5

xy <- data.frame(d1 = d1, d2 = d2)

library(tidyr)
xy <- gather(xy)

ggplot(xy, aes(x = value, fill = key)) +
  geom_density(kernel = "gaussian", alpha = 0.1) +
  geom_vline(xintercept = single_data)

在此处输入图片说明

You can do this:

require(ggplot2)
df <- data.frame(density=c(rnorm(50, mean=5), rnorm(50, mean=7)),
                 name=c(rep('d1', 50), rep('d2', 50)))

single_data = 5.5
max_y = max(max(density(d1[,1])$y), max(density(d2[,1])$y))

p1 <- ggplot(data=df) +
        geom_density(aes(x=density, group=name, colour=name, fill=name), kernel='gaussian', alpha=.5) + 
        geom_segment(aes(x=single_data, xend=single_data, y=0, yend=max_y), colour='blue') +
  scale_color_manual('Legend Name', labels=c('density 1', 'density 2'), values=c('blue', 'green')) +
  scale_fill_manual('Legend Name', labels=c('density 1', 'density 2'), values=c('blue', 'green')) +
        xlab("Count") + ylab("Density") + ggtitle('Main Title') +
        theme(legend.position='right')
p1

You have to build decent dataframes before ploting them. That's the key to the ggplot superiority :p. Here you vertical segment is not included in the legend. If you want it to be so, you have to use the color aesthetic for the segment and the fill aesthetic for the densities (instead of both for the densities as it is in the example).

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