如何有条件地突出显示 ggplot2 分面图中的点 - 将颜色映射到列 [英] How to conditionally highlight points in ggplot2 facet plots - mapping color to column

查看:18
本文介绍了如何有条件地突出显示 ggplot2 分面图中的点 - 将颜色映射到列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,我创建了两个系列的点并使用 ggplot2 绘制它们.我还根据他们的价值观强调了几点

In the following example I create two series of points and plot them using ggplot2. I also highlight several points based on their values

library(ggplot2)
x <- seq(0, 6, .5)
y.a <- .1 * x -.1
y.b <- sin(x)
df <- data.frame(x=x, y=y.a, case='a')
df <- rbind(df, data.frame(x=x, y=y.b, case='b'))
print(ggplot(df) + geom_point(aes(x, y), color=ifelse(df$y<0, 'red', 'black')))

这是结果

现在我想把两个case分成两个方面,保持高亮方案

Now I want to separate the two cases into two facets, keeping the highlighting scheme

> print(ggplot(df) + geom_point(aes(x, y), color=ifelse(df$y<0, 'red', 'black')) + facet_grid(case ~. ,))
Error: Incompatible lengths for set aesthetics: colour

如何实现?

推荐答案

你应该把 color=ifelse(y<0, 'red', 'black') 放在 aes(),所以颜色会根据每个facet中的y值独立设置.如果颜色在 aes() 之外设置为向量,则在两个方面使用相同的向量(具有相同的长度),然后您会得到错误,因为颜色向量的长度与数据点的数量一样大.

You should put color=ifelse(y<0, 'red', 'black') inside the aes(), so color will be set according to y values in each facet independently. If color is set outside the aes() as vector then the same vector (with the same length) is used in both facets and then you get error because length of color vector is larger as number of data points.

然后你应该添加 scale_color_identity() 以确保颜色名称被直接解释.

Then you should add scale_color_identity() to ensure that color names are interpreted directly.

ggplot(df) + geom_point(aes(x, y, color=ifelse(y<0, 'red', 'black'))) + 
   facet_grid(case ~. ,)+scale_color_identity()

这篇关于如何有条件地突出显示 ggplot2 分面图中的点 - 将颜色映射到列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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