根据变量更改单个geom_ribbon()的颜色 [英] Change colors of a single geom_ribbon() depending on variable

查看:51
本文介绍了根据变量更改单个geom_ribbon()的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一个geom_ribbon(),在此我将带的颜色作为变量的条件.

I want to plot a geom_ribbon() where I make the color of the band conditional on a variable.

示例:

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

哪个创建了

这会创建两个单独的波段,但我只想更改一个组合波段的颜色.

This creates two separate bands, but I only want to change the colors of one combined band.

推荐答案

由于在ggplot中每行不能有超过一种颜色,因此我们可以将数据扩展为相互连接的多行,因此它们看起来像是一条线.然后,我们可以为每个部分分配一种颜色.

Since in ggplot you cannot have more than one color per line, we can expand the data into multiple lines that connect to each other so they appear to be one line. Then we can assign each section a color.

为确保它们看起来已连接,我们必须扩展数据,以使下一组的起点和上一组的终点具有相同的xy坐标,但组不同:

To make sure they appear connected, we have to expand the data so that the start of the next group and the end of the previous group have the same x and y coordinates, but different groups:

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

将此内容与原始的无色行进行比较:

Compare this to the original, uncolored line:

ggplot(df, aes(x = year)) +
  geom_ribbon(aes(ymin = lower, ymax = upper))

一个音符-我lapplyna.locf,所以类型没有改变.我知道您可以na.locf(df_plot).

One note - I lapply with the na.locf so the type doesnt get changed on me. I am aware you can do na.locf(df_plot).

这篇关于根据变量更改单个geom_ribbon()的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆