如何正确突出显示使用构面的ggplot2图中的点 [英] How to properly highlight points in ggplot2 plots that use facets

查看:190
本文介绍了如何正确突出显示使用构面的ggplot2图中的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的例子中,我创建了两个系列的点,并使用 ggplot2 来绘制它们。我还根据它们的值强调了几点:$ b​​
$ b pre $ library $(gplot2)
x < - seq(0,6, 5)
ya < - .1 * x-1
yb < - sin(x)
df < - data.frame(x = x,y = ya, (df,data.frame(x = x,y = yb,case ='b'))
print(ggplot(df)+ geom_point( aes(x,y),color = ifelse(df $ y <0,'red','black')))

这里是结果



现在我想将两个 case s分为两个方面,保持突出显示方案

 > print(ggplot(df)+ geom_point(aes(x,y),color = ifelse(df $ y <0,'red','black'))+ facet_grid(case〜。))
错误:不符合设定美学的长度:颜色

这是如何实现的?

解决方案

您应该在内部放置 color = ifelse(y <0,'red','black') aes(),所以颜色将根据每个小平面中的y值独立设置。如果将颜色设置为aes()以外的矢量,则在两个构面中使用相同的矢量(具有相同的长度),然后由于颜色矢量的长度随着数据点的数量变大而出现错误。



然后,您应该添加 scale_color_identity()以确保直接解释颜色名称。

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


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

And here is the result

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

How can this be acheived?

解决方案

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.

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天全站免登陆