在R(ggplot2)中创建密度图的手动图例 [英] create a manual legend for density plots in R (ggplot2)

查看:615
本文介绍了在R(ggplot2)中创建密度图的手动图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为图表添加一个图例。我在网上找到的所有解决方案都使用scale_color_manual - 但它不适合我。传说在哪里?
这里是我的代码:

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


解决方案

<如果由于某种原因,你绝对需要这两个geoms来承担不同的数据源,请将 aes()中的 color = XXX code>,然后使用命名向量手动定义颜色:

  ggplot()+ 
geom_density(aes(x = rnorm(100),color ='first'))+
geom_density(aes(x = rnorm(100),color ='second'))+
xlab )+ ylab(Density)+ ggtitle('Age Densities')+
主题(legend.position ='right')+
s我们可以通过下面的例子来说明这个问题:a。cale_color_manual(values = c('first'='red','second'='blue'))


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

解决方案

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

这篇关于在R(ggplot2)中创建密度图的手动图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆