如何在具有相同“y”的行之间进行着色?

时间:2017-03-28 15:58:05

标签: r ggplot2 area

我花了几个小时在geom_polygon& geom_ribbon和我无法让它工作。我希望遮蔽两条线之间的区域(我研究了很多)。看,图的两个轴都是数字,两条线共用同一个y轴,因此,我不能让它工作计算ymin也不能YMAX。有什么想法吗?我会完全欣赏它。这是我的代码:

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)

结果图: enter image description here

我的数据:

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")

1 个答案:

答案 0 :(得分:6)

在我看来,这是一个罕见的场合,可以更好地将数据集放在“广泛”的范围内。格式。

我会使用geom_linegeom_point的长格式,然后切换为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

请注意inherit.aes = FALSE,因为否则geom_ribbon会尝试使用映射到Score的{​​{1}}列。

数据:

y