【问题标题】:Add an arrow to a facetted ggplot, outside the plot, on just one facet将箭头添加到多面 ggplot,在情节之外,仅在一个方面
【发布时间】:2020-12-04 05:24:01
【问题描述】:

我的情节目前看起来像这样

我希望 Y 轴左侧有一个指向该轴的箭头,以及箭头旁边的文本。

到目前为止,这是我的代码:

co2_diff_2050 %>%   
  ggplot( aes( Year, MTC, fill = Sector ) ) +
  geom_bar( position = "stack", stat = "identity" ) +
  scale_fill_manual( values = CO2_sector_color ) +
  scale_x_continuous( name = "Year", breaks = c( 2050 ) ) +
  scale_y_continuous( name = "MTC", breaks = c( 0, 5, 10 ), limits = c( -1, 13 ) ) +
  geom_segment(aes(x = 2049.5, y = maryland_80goal, xend = 2049.8, yend = maryland_80goal),
            arrow = arrow(length = unit(0.5, "cm"))) +
  geom_errorbar( aes( ymin = net_diff, ymax = net_diff ), color = "gray30", linetype = "longdash", width = 1, size = 1 ) +
  geom_hline( yintercept = 0 ) +
  theme_bw() +
  guides( fill = guide_legend( ncol = 1 ) ) +
  theme( legend.position = "right" ) +
  labs( title = "Maryland Remaining CO2 Emissions by Sector in 2050",
        caption = "Arrow indicates Maryland's 2050 GHG emissions reduction goal
        Dashed gray line indicates emissions with biomass offset") +
  facet_wrap( ~ Scenario, nrow = 1 )

【问题讨论】:

  • 您的意思是箭头应该位于绘图的外部/左侧并指向 y 轴?
  • @zoowalk 正确!我将添加一张我的目标的图片

标签: r ggplot2


【解决方案1】:

这是一种 hacky 解决方案,但它似乎有效。我们制作了一个没有任何映射美学的geom_segment(),因此不会在这些上训练尺度。但是,我们确实添加了 data 参数,只是为了指示箭头应该出现在哪个面板旁边。现在通常不会出现,因为它超出了范围,但我们可以设置clip = "off" 来显示它。

library(ggplot2)

ggplot(mpg, aes(displ, hwy)) + 
  geom_point() +
  geom_segment(
    # Change the 0 and 25's to be appropriate to your data
    x = 0, xend = -Inf, y = 25, yend=  25,
    arrow = arrow(length = unit(5, "pt")),
    # Add facetting variable appropriate to your data
    data = data.frame(cyl = 4)
  ) +
  coord_cartesian(clip = "off") +
  facet_wrap(~ cyl, ncol = 4)

由reprex package (v0.3.0) 于 2020 年 12 月 3 日创建

【讨论】:

  • 谢谢!一个问题。对于data = data.frame( cyl = 4 ),我尝试了各种面板指示器,例如data = data.frame( Scenario == "highEV" ) 、data = data.frame( Scenario = highEV ) ,但我得到FUN(X[[i]], ...) 中的错误:找不到对象'Sector'。我解释错了吗?我想要第一个面板的箭头,当场景是 highEV 时。
  • data = data.frame(Scenario = "highEV") 听起来对我来说是正确的。我怀疑的错误可能是由于继承的美学,所以可能你可能想将inherit.aes = FALSE 添加到段中。或者,您也可以将fill = Sector 规范移动到geom_bar(aes(fill = Sector), ...),然后它不应该干扰下游。这些我都没有测试过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
  • 2016-11-29
相关资源
最近更新 更多