0

line chart I'm working with the line chart above, which is generated by the code:

ggplot(data=df) + geom_line(aes(x=date,y=germany,col="Germany")) +
  geom_line(aes(x=date,y=korea,col="Coreia do Sul"))  +  
  scale_color_manual(values=c("black","blue")) +
  ylab("Confirmed cases")

The first lines of the dataframe df are:

  date             germany  korea
1 2020-01-22       0        1
2 2020-01-23       0        0
3 2020-01-24       0        1
4 2020-01-25       0        0
5 2020-01-26       0        1
6 2020-01-27       1        1

I would like to create colored regions below the curves, like this: line chart with regions Is it possible? Thanks in advance!

Martin Gal
  • 16,640
  • 5
  • 21
  • 39
  • 1
    Hi there, welcome to Stack Overflow. The graph shown in the link has more than 1 value for each point on the x-axis. It also has the colour band set at a specific y-axis value, so there is a yellow horizontal band between 300 and 1000. Is that what you want - colour strips by y-axis values, with the Germany and Korea counts plotted as overlaid lines? – Michelle May 10 '20 at 19:53
  • Exactly. My goal is to have a green region below 300, a yellow region between 300 and 1000 and red for values above 1000. Just like in the last image. – mathguy_666 May 10 '20 at 21:25
  • 1
    Does the geom_ribbon command in ggplot work for you? I've not used it myself. Here are two answers that reference the geom_ribbon option that might help https://stackoverflow.com/questions/37277729/ggplot2-fill-color-behaviour-of-geom-ribbon and https://stackoverflow.com/questions/49310317/ggplot2-geom-ribbon-decouple-linetype-aesthetic-in-legend-from-color. You'll need to change the colour options to get the ones you want, because the default aren't the same. – Michelle May 10 '20 at 21:50
  • Knowing about the geom_ribbon() was exactly what i needed. Thank you all for the help! – mathguy_666 May 10 '20 at 23:33

1 Answers1

1

Here is one basic approach. Just as an illustrative proof of concept, let's take the two functions y1(x) = sin(x) + 1 and y2(x) = max(0, 8cos(x)exp(-.3x)) over [0, 5*pi] to represent some arbitrary data:

# libraries dplyr, tibble
df <- seq(0, 5*pi, by=.01) %>% 
    enframe(value="x") %>%
    mutate(y1=sin(x) + 1, y2=pmax(0, 8 * cos(x) * exp(-.3 * x) + 1));

Then we can use (for arbitrary breakpoints at 0.5 and 1.5):

df %>%
  mutate(ymax=pmax(y1, y2)) %>%
  ggplot(aes(x, y1)) + 
  geom_ribbon(aes(ymin=pmin(ymax, 0),   ymax=pmin(ymax, 0.5)), fill='green') +
  geom_ribbon(aes(ymin=pmin(ymax, 0.5), ymax=pmin(ymax, 1.5)), fill='yellow') +
  geom_ribbon(aes(ymin=pmin(ymax, 1.5), ymax=pmin(ymax, max(ymax))), fill='red') +
  geom_point() +
  geom_point(aes(y=y2), color='blue')

Yielding colored regions under the curves:

Rplot output

drf
  • 8,461
  • 32
  • 50