Home > Back-end >  How to shade bars in bar graph by axis?
How to shade bars in bar graph by axis?

Time:10-24

How to shade this graph by 2008 as a cut point? Like, before 2008 all share one color, after 2008 use another color.

image

CodePudding user response:

you need a vector that is the length of the amount of bars that you have that supplies the color. you could try something like this:

color = ifelse(date < 2008, 'red', 'green')

you have to adjust the test accordingly.

Then you provdide the color to the plot

ggplot(aes(fill = color))

CodePudding user response:

you need to use annotate function with rect as the option for geom:

# Add rectangles
p   annotate(
  geom = "rect", 
  xmin=c(2,4), 
  xmax=c(3,5), 
  ymin=c(20,10), 
  ymax=c(30,20), 
  alpha=0.2, 
  color="blue", 
  fill="blue"
)

See https://www.r-graph-gallery.com/233-add-annotations-on-ggplot2-chart.html

  • Related