根据变量更改单个geom_ribbon()的颜色

根据变量更改单个geom_ribbon()的颜色,r,ggplot2,R,Ggplot2,我想绘制一个geom_ribbon(),在这里,我使带的颜色以变量为条件 例如: library(dplyr) library(ggplot2) df <- tribble( ~year, ~lower, ~upper, ~type, 2001, 150, 222, "A", 2002, 53, 64, "A", 2003, 31, 64, "B", 2004, 10, 18, "B", 2005, 30, 49, "B", 2006, 37, 43, "A"

我想绘制一个
geom_ribbon()
,在这里,我使带的颜色以变量为条件

例如:

library(dplyr)
library(ggplot2)

df <- tribble(
  ~year, ~lower, ~upper, ~type,
  2001, 150, 222, "A",
  2002, 53, 64, "A",
  2003, 31, 64, "B",
  2004, 10, 18, "B",
  2005, 30, 49, "B",
  2006, 37, 43, "A",
  2007, 54, 77, "B",
  2008, 58, 89, "A",
  2009, 50, 111, "A",
  2010, 40, 81, "A",
  2011, 49, 63, "A"
)

ggplot(df, aes(x = year)) +
  geom_ribbon(aes(ymin = lower, ymax = upper, fill = type))
库(dplyr)
图书馆(GG2)

df由于在
ggplot
中,每行不能有一种以上的颜色,因此我们可以将数据扩展为多行,这些行相互连接,使它们看起来像一行。然后我们可以为每个部分指定一种颜色

为了确保它们看起来是连接的,我们必须扩展数据,以便下一组的开始和上一组的结束具有相同的
x
y
坐标,但不同的组:

library(zoo)
library(data.table)
df$group <- rleid(df$type)
df_plot <- head(do.call(rbind, by(df, df$group, rbind, NA)), -1)
df_plot[,c("group","type")] <- lapply(df_plot[,c("group","type")], na.locf)
df_plot[] <- lapply(df_plot, na.locf, fromLast = TRUE)

ggplot(df_plot, aes(x = year)) +
  geom_ribbon(aes(ymin = lower, ymax = upper, fill = type, group = group))


一个注意事项是-I
lappy
带有
na.locf
,因此类型不会在我身上改变。我知道您可以使用
na.locf(df\u plot)

更改一个组合带的颜色是什么意思?您可以使用
scale\u fill\u manual
来设置您想要的填充颜色
ggplot(df, aes(x = year)) +
  geom_ribbon(aes(ymin = lower, ymax = upper))