How do I color the same "y" s between the lines?

I've spent a couple of hours trying between geom_polygon and geom_ribbon and I just can't seem to get it to work. I'm looking to shade the area between the two lines (I've explored it quite a bit). Let's see, both axes of the graph are numeric and the two lines have the same y-axis, so I can't get it to work by calculating ymin and yy. Any guys ideas? I would totally appreciate it. Here is my code:

ggplot(npsmelt,aes(Score,Unresolved)) + 
    geom_line(aes(linetype=Metric, color=Metric)) +
    theme(legend.position="top", legend.title = element_blank()) +
    geom_point(aes(color=Metric)) +
    theme(plot.caption=element_text(size=8, margin=margin(t=10))) + 
    scale_x_continuous(breaks=seq(54,70,1)) + 

    geom_ribbon(data=subset(npsmelt, 
         Score[Metric=="Old.NPS"]<Score[Metric=="New.NPS"]),
         aes(ymin =0, ymax =..y..), alpha=0.10)

      

The resulting graph is: enter image description here

My details:

Unresolved  Metric  Score
    5   New.NPS 66.48
    6   New.NPS 65.32
    7   New.NPS 64.16
    8   New.NPS 63
    9   New.NPS 61.84
   10   New.NPS 60.68
    5   Old.NPS 68.5 
    6   Old.NPS 62.28
    7   Old.NPS 61.74
    8   Old.NPS 61.41
    9   Old.NPS 61.67
   10   Old.NPS 60.42

      

dput

:

structure(list(Unresolved = c(5L, 6L, 7L, 8L, 9L, 10L, 5L, 6L, 
7L, 8L, 9L, 10L), Metric = c("New.NPS", "New.NPS", "New.NPS", 
"New.NPS", "New.NPS", "New.NPS", "Old.NPS", "Old.NPS", "Old.NPS", 
"Old.NPS", "Old.NPS", "Old.NPS"), Score = c(66.48, 65.32, 64.16, 
63, 61.84, 60.68, 68.5, 62.28, 61.74, 61.41, 61.67, 60.42)), .Names = c("Unresolved", 
"Metric", "Score"), row.names = c(NA, -12L), class = "data.frame")

      

+3


source to share


1 answer


This seems to me to be one of the rare cases where it is better to have a dataset in a "wide" format.

I use the long format for geom_line

and geom_point

, and then move on to the wide format for geom_ribbon

.

library(ggplot2)
library(tidyr)

ggplot(df, aes(Unresolved, Score, group = Metric, color = Metric)) +
  geom_line() +
  geom_point() +
  geom_ribbon(data = spread(df, Metric, Score), 
              aes(x = Unresolved, ymin = New.NPS, ymax = Old.NPS), 
              alpha = .2,
              inherit.aes = FALSE)

      

enter image description here



Note inherit.aes = FALSE

, this is necessary because otherwise it geom_ribbon

will try to use the column Score

that maps to y

.

Data:

df <- structure(list(Unresolved = c(5L, 6L, 7L, 8L, 9L, 10L, 5L, 6L, 
7L, 8L, 9L, 10L), Metric = c("New.NPS", "New.NPS", "New.NPS", 
"New.NPS", "New.NPS", "New.NPS", "Old.NPS", "Old.NPS", "Old.NPS", 
"Old.NPS", "Old.NPS", "Old.NPS"), Score = c(66.48, 65.32, 64.16, 
63, 61.84, 60.68, 68.5, 62.28, 61.74, 61.41, 61.67, 60.42)), .Names = c("Unresolved", 
"Metric", "Score"), row.names = c(NA, -12L), class = "data.frame")

      

+6


source







All Articles