ggr图中geom_路径的条件着色
我有以下简化数据框,其中包含四条路径:ggr图中geom_路径的条件着色,r,ggplot2,R,Ggplot2,我有以下简化数据框,其中包含四条路径: df <- read.table(text="id x y a 1 1 a 2 2.0 a 2 3.1 a 3.2 4 b 1.0 1 b 2 0 b 2 -1 b 3 -3
df <- read.table(text="id x y
a 1 1
a 2 2.0
a 2 3.1
a 3.2 4
b 1.0 1
b 2 0
b 2 -1
b 3 -3
c 1 1
c 0 0
c 0 -1
c -1 -2
d 1 1
d 0 1
d -1 0
d -2 0", header=TRUE)
问题
如何将Y值超过2的路径涂成红色(如果有多条路径,则更好地涂成红色),同时将其他路径涂成不同的灰色?我可以手动改变线条的颜色,但我有3到50多条路径的绘图,因此我正在寻找一种更自动化的解决方案。一种方法是在将数据帧传递到
ggplot
之前为每条路径添加一个颜色列:例如,您可以在luv_colors
中为每条路径指定一个颜色名称,可以传递到标识
色标中。下面的示例使用dplyr
实现这一点
n_ids <- length(unique(df$id))
group_by(df, id) %>%
mutate(col = if (any(y>2)) "red" else paste0("gray", round(match(id, letters) * 60/n_ids))) %>%
ungroup() %>%
ggplot() +
geom_path(aes(x, y, colour = col, lty = id)) +
scale_colour_identity()
这还具有路径数量不受灰度颜色数量限制的优点
如果路径ID具有有意义的顺序,则可以使用不同于默认值的调色板,例如scale\u color\u brewer()
或scale\u color\u viridis\u d()
编辑:您还可以引入几种红色,并以类似于我处理不同路径的灰度的方式使用它们。出于两个原因,我仍然建议不要这样做,而是支持我的替代方案:
group_by(df, id) %>%
mutate(col = if (any(y>2)) "red" else "black") %>%
ungroup() %>%
ggplot() +
geom_path(aes(x, y, colour = col, group = id)) +
scale_colour_identity()
我不太清楚您的问题,但您可以创建一个条件,然后根据它为项目上色
df <- read.table(text="id x y
a 1 1
a 2 2.0
a 2 3.1
a 3.2 4
b 1.0 1
b 2 0
b 2 -1
b 3 -3
c 1 1
c 0 0
c 0 -1
c -1 -2
d 1 1
d 0 1
d -1 0
d -2 0", header=TRUE)
df$condition <- ifelse(df$y>2,"Yes","No")
ggplot(data = df) + geom_path(aes(x = x, y = y, color = condition))
df
group_by(df, id) %>%
mutate(col = if (any(y>2)) "red" else "black") %>%
ungroup() %>%
ggplot() +
geom_path(aes(x, y, colour = col, group = id)) +
scale_colour_identity()
df <- read.table(text="id x y
a 1 1
a 2 2.0
a 2 3.1
a 3.2 4
b 1.0 1
b 2 0
b 2 -1
b 3 -3
c 1 1
c 0 0
c 0 -1
c -1 -2
d 1 1
d 0 1
d -1 0
d -2 0", header=TRUE)
df$condition <- ifelse(df$y>2,"Yes","No")
ggplot(data = df) + geom_path(aes(x = x, y = y, color = condition))