r - 使用多个 ggplot2 geom_crossbar 参数时重置颜色美学
问题描述
我试图控制两个单独调用的颜色,geom_crosbar
第一个图使用绿色,第二个图使用蓝色。但是,我从第二次geom_crossbar
调用 Scale for 'fill' 中得到警告:
警告:为“填充”添加另一个比例,它将替换现有比例。
这是我的代码示例:
my.data %>%
ggplot(aes(site, npp_nofert)) +
geom_crossbar(aes(ymin=npp_nofert-npp.sd_nofert,ymax=npp_nofert+npp.sd_nofert,
fatten=1.0,fill=period),position='dodge', alpha=0.5) +
scale_fill_brewer(palette="Greens") +
#labs(y=expression(paste("MMM %",Delta," (+/- 1",sigma,")")), x="", fill="", title="") + theme_bw() +
labs(y="",x="", fill="", title="") + theme_bw() +
theme(legend.key.size=unit(1.0,"cm"),legend.direction="horizontal",legend.position=c(0.3,0.05),
axis.text.x=element_blank(),axis.ticks.x=element_blank(),
plot.title=element_text(size=12,margin=margin(t=5,b=-20)), legend.spacing=unit(0,"cm"),
text = element_text(size=15)) +
new_scale_fill() +
geom_crossbar(aes(ymin=npp_fert-npp.sd_fert,ymax=npp_fert+npp.sd_fert, fatten=1.0,fill=period),
position='dodge',alpha=0.5) +
scale_fill_brewer(palette="Blues")
不幸的是,我无法dput()
获取数据,因为我无权这样做。如何将第一个情节设置为绿色,第二个情节设置为蓝色?另外,刚刚注意到对 alpha 的调用在图例中。如何删除它?
注:1980 年至 1999 年期间,只有一个小区(即不处理),因此该期间不会有重叠小区。x 轴代表研究地点,我可以稍后修复标签。
解决方案
解决这个问题的一般方法是使用ggnewscale
包,它允许您在绘图过程中的某个时刻“重置”美学。
由于没有数据可供使用,我将编造一些与您在上面显示的内容有模糊相似之处的虚拟数据。
library(ggplot2)
library(ggnewscale)
df <- data.frame(
x = 1:5,
blue_low = 1:5,
blue_mid = 2:6,
blue_high = 3:7,
green_low = 0:4,
green_mid = 2:6,
green_high = 4:8
)
ggplot(df, aes(x = 1, group = x)) +
geom_crossbar(aes(ymin = green_low, y = green_mid, ymax = green_high,
fill = as.factor(x)),
position = "dodge", alpha = 0.5) +
scale_fill_brewer(palette = "Greens") +
new_scale_fill() + # Important to put this after you defined the first scale
geom_crossbar(aes(ymin = blue_low, y = blue_mid, ymax = blue_high,
fill = paste0(x, "_blue")), # paste to differentiate scale
position = "dodge", alpha = 0.5) +
scale_fill_brewer(palette = "Blues")
由reprex 包(v0.3.0)于 2020-06-18 创建
new_scale_fill()
我相信在你的绘图代码中将它放在正确的位置不会太难,我认为这是在scale_fill_brewer(palette="Greens")
.
推荐阅读
- reactjs - React JS - Material UI:图标不可见
- python - python pandas如何每n行和每n行获取数据?
- delphi - Delphi 项目不再通过资源 DLL 识别 DPI
- python - 在python中将散点图变成直方图
- vue.js - Vuetify v-treeview 不删除节点
- android - 从服务访问命名的 sharedpreference
- mysql - MySQL 使用日期范围优化查询
- parquet - 如何读取使用 DELTA_BYTE_ARRAY 编码的镶木地板文件?
- node.js - 在 heroku 上使用 Express.js 提供静态文件。文件在 Heroku 中的位置?
- python - 在 Docker 容器中运行时,Django 静态文件不提供服务