首页 > 解决方案 > 使用多个 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 轴代表研究地点,我可以稍后修复标签。

标签: rggplot2tidyverse

解决方案


解决这个问题的一般方法是使用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").


推荐阅读