create a manual legend for density plots in R (ggplot2)

寵の児 提交于 2019-12-13 03:24:50

问题


I want to add a legend to my graph. All solutions I found online use scale_color_manual - but it's not working for me. Where is the legend? Here is my code:

library(ggplot2)
ggplot() +
  geom_density(aes(x = rnorm(100)), color = 'red') +
  geom_density(aes(x = rnorm(100)), color = 'blue') +
  xlab("Age") + ylab("Density") + ggtitle('Age Densities')
  theme(legend.position = 'right') +
  scale_color_manual(labels = c('first', 'second'), values = c('red', 'blue'))

回答1:


If for some reason you absolutely need the two geoms to take on different data sources, move the color = XXX portion inside aes() for each, then define the colors manually using a named vector:

ggplot() +
  geom_density(aes(x = rnorm(100), color = 'first')) +
  geom_density(aes(x = rnorm(100), color = 'second')) +
  xlab("Age") + ylab("Density") + ggtitle('Age Densities') +
  theme(legend.position = 'right') +
  scale_color_manual(values = c('first' = 'red', 'second' = 'blue'))




回答2:


Your data are not formatted correctly and you are basically creating two separate plots on a common "canvas", please see the code below (creation of the df is the crucial part):

library(ggplot2)

df <- data.frame(
  x = c(rnorm(100), runif(100)),
  col = c(rep('blue', 100), rep('red', 100))
)

ggplot(df) +
  geom_density(aes(x = x, color = col)) +
  xlab("Age") + ylab("Density") + ggtitle('Age Densities') + 
  theme(legend.position = 'right') +
  scale_color_manual(labels = c('first', 'second'), values = c('red', 'blue'))


来源:https://stackoverflow.com/questions/46821524/create-a-manual-legend-for-density-plots-in-r-ggplot2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!