1

screenshot of plot

I want to illustrate the textual area like the variable one.

library(ggplot2)
library(ggpattern)

# Reshape the data into a long format
data_long <- data %>%
  gather(key = "variable", value = "value", NI, GP, SA, CF)

ggplot() +
  #geom_line(data = data_long, aes(x = date, y = value, linetype = variable),size=1) +
  #scale_linetype_manual(values = c("solid", "dashed", "dotted", "dotdash")) +
  geom_ribbon_pattern(data = data, aes(x = date, ymin = 0, ymax = CF), fill = "gray95",
                      color = "white", 
                      pattern = "crosshatch",
                      pattern_fill = "white",
                      pattern_angle = 45,
                      pattern_density = 0.01,
                      pattern_spacing = 0.01) +
  geom_ribbon_pattern(data = data, aes(x = date, ymin = CF, ymax = NI), fill = "gray95",
                      color = "white", 
                      pattern = "stripe",
                      pattern_fill = "gray40",
                      pattern_angle = 45,
                      pattern_density = 0.01,
                      pattern_spacing = 0.01) +
  geom_ribbon_pattern(data = data, aes(x= date, ymin= NI, ymax= GP), fill= "gray95",
                      color= "transparent",
                      linetype="dashed",
                      pattern= "stripe",
                      pattern_fill= "gray80",
                      pattern_angle= 90,
                      pattern_density= 0.01,
                      pattern_spacing= 0.01) +
  geom_ribbon_pattern(data= data, aes(x= date, ymin= GP, ymax= SA), fill= "gray95",
                      color= "white", 
                      pattern= "stripe",
                      pattern_fill= "gray80",
                      pattern_angle= 135,
                      pattern_density= 0.01,
                      pattern_spacing= 0.01)+
  geom_line(data = data_long, aes(x = date, y = value, linetype = variable),size=1) +
  scale_linetype_manual(values = c("solid", "dashed", "dotted", "dotdash")) +  
  scale_pattern_manual(values=c("crosshatch","stripe","stripe","stripe"))

For data, data consist of four columns, named CF,GP,NI,SA all number is created randomly.

jsotola
  • 2,238
  • 1
  • 10
  • 22
s Murasame
  • 11
  • 3
  • 2
    Instead of specifying `pattern` directly in each layer, you need to _map_ the pattern aesthetic. So, move `pattern` to _inside_ `aes` and map it to the text you want to see in your legend. For example, in your first layer this will be `pattern = "CF"` inside `aes`. If you do this, a legend will appear. – Allan Cameron Aug 19 '23 at 11:28

0 Answers0