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

查看:72
本文介绍了如何有条件地突出显示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()内,这样颜色将根据每个构面中的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天全站免登陆