r - 更改 ggplot 图例渐变
问题描述
我有这个关于不同基因型平均增长率的数据集:
Genotype desv mean Rank
<fct> <dbl> <dbl> <dbl>
ENG2 0.345 4.29 7
ENG20 0.255 3.90 9
ENG22 0.185 4.19 8
ENG24 0.341 3.84 10
ENG25 0.195 3.51 12
ENG3 0.267 4.38 6
ENG32 0.262 3.61 11
ENG4 0.223 4.49 4
ENG5 0.359 5.13 2
ENG7 0.122 4.49 5
ENG8 0.182 4.90 3
ENG9 0.459 5.28 1
下面的代码制作一个ggplot图:
ggplot(growth2)+
geom_col(aes(x=Rank, y=mean, fill=mean), width=0.7, color="Black")+
geom_errorbar(aes(x=Rank, ymin=mean-desv, ymax=mean+desv), position = position_dodge(width=0.9),width=0.4, alpha=1)+
theme_classic()+
theme(axis.text.x=element_text(angle = 90, hjust =2, vjust = 0.5, family="sans", size=12, color="Black"))+
theme(axis.ticks.x = element_blank())+
xlab("")+
ylab(expression(paste("AGR (cm "," ", year^-1,")", sep="")))+
theme(axis.line.x = element_blank())+
theme(axis.text.y=element_text(family="sans", size=12, color="Black"))+
theme(axis.title.y= element_text(margin=margin(t=0, r=10, b=0, l=0)))+
scale_y_continuous(breaks=c(0, 1, 2, 3, 4, 5, 6), limits = c(0,6))+
scale_fill_gradient(low="red", high="green", name="")+
geom_hline(yintercept = 0, color="Black")+
theme(legend.position = c(0.5,1), legend.direction = "horizontal")+
theme(legend.text = element_blank())+
theme(plot.margin = margin(1,0,0,0, unit = "cm"))+
scale_x_continuous(breaks=c(1,2,3,4,5,6,7,8,9,10,11,12),labels = c("ENG 9 ", "ENG 5 ", "ENG 8 ", "ENG 4 ", "ENG 7 ", "ENG 3 ", "ENG 2 ", "ENG 22", "ENG 20", "ENG 24", "ENG 32", "ENG 25"))
然而我的传奇不是我想要的方式。绿色部分(高增长率)应该在左边。我在 guides_legend 中尝试了相反的操作,但没有成功。我也希望图例的大小占据图表的长度。我在 ggplot 中没有发现任何关于图例长度的争论。
有人可以帮助我吗?或者指出是否可以进行这些图例更改。
解决方案
为了切换图例中的颜色顺序,我交换了这一行的颜色名称:
scale_fill_gradient(low="green", high="red", name="")+
为了在整个 x 轴上加宽图例,我legend.key.width
在你之后使用了theme()
:
theme(plot.margin = margin(1,0,0,0, unit = "cm"),
legend.key.width= unit(4, 'cm'))+
推荐阅读
- mongodb - Mongodb $lookup 加入所有集合而不是匹配对象
- postgresql - tar 转储中的 sql 脚本文件的用途是什么?
- java - 我们可以设计一个通用函数来完成整数和字符串的加法吗?
- here-api - 通行费增值税 HERE API
- bash - 从 shell 脚本中,如何过滤掉与 .gitignore 匹配的文件?
- rxjs - RxJs 比赛功能 - 确保第一个发生的人获胜
- c - 使 fgets 跳过特殊字符
- html - 引导网格,中间内容粘在页面顶部
- android - 在用户按下呼叫按钮和用户开始听到呼叫声音之间获取事件
- javascript - Google Map API 不适用于 Angular 2