Maridee Weber
Maridee Weber

Reputation: 231

Add an arrow to a facetted ggplot, outside the plot, on just one facet

My plot currently looks like thisplot

And I want there to be a single arrow to left of the Y axis pointing at the axis, as well as text by the arrow.

enter image description here

Here is my code so far:

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 )

Upvotes: 1

Views: 1401

Answers (1)

teunbrand
teunbrand

Reputation: 38013

This is kind of a hacky solution but it seems to work. We make a geom_segment() without any mapped aesthetics, so that scales aren't trained on these. However, we do add the data argument, just to indicate which panel the arrow should appear next to. Now normally, this wouldn't appear because it is out of bounds, but we can set clip = "off" to show it anyway.

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)

Created on 2020-12-03 by the reprex package (v0.3.0)

Upvotes: 3

Related Questions