-->

创建中的R密度图的手动图例(GGPLOT2)(create a manual legend for

2019-10-29 02:25发布

我想一个传说添加到我的图表。 所有的解决方案,我发现在网上使用scale_color_manual - 但它不是为我工作。 哪里是传奇? 这里是我的代码:

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'))

Answer 1:

如果出于某种原因,绝对需要两个geoms承担不同的数据源,移动color = XXX内侧部分aes()为每个,然后使用名为向量手动定义的颜色:

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'))



Answer 2:

您的数据的格式不正确,你基本上是在一个共同的“画布”上创建两个单独的地块,请参见下面(的创建代码df是重要组成部分):

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'))


文章来源: create a manual legend for density plots in R (ggplot2)