r - 我可以在不使用 aes() 的情况下手动向 ggplot 添加图例吗?
问题描述
我用 stat_ecdf 函数做了一个 CDP 图,但我不能添加图例。这是 CDP 图的代码:
ggplot()+
stat_ecdf(data=df, aes(Apple), geom = "step", col ="red")+
stat_ecdf(data=df, aes(Ocean), geom = "step", col ="blue")+
stat_ecdf(data=df, aes(Tree), geom = "step", col ="green")+
stat_ecdf(data=df, aes(Citron), geom = "step", col ="yellow")+
stat_ecdf(data=df, aes(Sun), geom = "step", col ="orange")+
labs(y="Cumulative Probability",x="Proportion of samples (>1 FIB per 100 mL)",col="Legend")+
theme_classic()
情节出现,但没有传说。我想有一个传说,描述红线=苹果,蓝线=海洋等。谢谢。
解决方案
ggplot 可以更好地处理长格式的数据。您可以重塑数据,使 x 变量位于单个列中,并且有一列区分颜色,然后您可以在绘图中添加颜色列作为美学。您希望您的数据采用这种形式
df = bind_rows(
# apple df
data.frame(x=runif(100,-10,10),col_column='Apple',
stringsAsFactors = F),
# ocean df
data.frame(x=runif(100,0,20),col_column='Ocean',
stringsAsFactors = F),
# tree df
data.frame(x=rnorm(100,mean=0,sd=2),col_column='Tree',
stringsAsFactors = F)
)
head(df)
# x col_column
# 1 -3.3221018 Apple
# 2 -9.8157569 Apple
# 3 9.7496057 Apple
# 4 -8.4488035 Apple
# 5 -8.4584002 Apple
# 6 0.9613705 Apple
我实际上看不到您的数据,但根据您使用它的方式,我假设它只有 columns Apple
、Ocean
、Tree
等。如果是这样,您可以使用 dplyr 的 gather 函数以长格式重塑。
df = dplyr::gather(df,key='col_column',value='x')
然后你可以像这样重新安排你的 ggplot 调用。
ggplot(data=df,mapping=aes(x,color=col_column)) +
stat_ecdf(geom='step') +
scale_color_manual(values=c('Apple'='red','Ocean'='blue','Tree'='green'))
这可以防止你重写stat_ecdf
你想要的每一列/颜色。
推荐阅读
- ruby-on-rails - Nginx, Certbot & Docker Compose: /etc/nginx/user.conf.d/*.conf: 没有这样的文件或目录
- python - 执行.py文件,在for循环中调用python函数
- html - 无法删除 Laravel Blade 表中的部门名称
- memory-management - 假设有一台 18 位地址空间的计算机,单元大小为 8 位,那么最小和最高地址是多少?
- pip - 获取python文件的requirements.txt并将其安装到virtualenv中
- flutter - Flutter PageView 内存泄漏
- java - 使用 GraalVM Native Image 代替混淆
- java - 无法访问“org.gradle.api.artifacts.dsl.DependencyHandler”的超类型“java.lang.Object”
- python - 为什么 dict.pop() 在这里从两个字典中删除值而只指定一个?
- python - 使用 numpy Where 的多个 OR 条件