基于值的Geom_jitter颜色 [英] Geom_jitter colour based on values

查看:129
本文介绍了基于值的Geom_jitter颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以根据数值为箱形图上的抖动点上色,例如:

Is there a way to color the jitter points on a boxplot based on a numeric value, so for example:

ggplot(data, aes(y = y_var, x = x_var)) +
  geom_jitter(size = 2, aes(color = ifelse(y_var < 5, "red", "black)))

我添加了这个可重现的示例,但效果不佳(绘图中的颜色与抖动调用不符):

I've added this reproducible example that doesn't quite work (the colors on the plot don't correspond to the jitter call):

a <- rnorm(100, mean = 5, sd = 1)
b <- as.factor(sample(0:1, 100, replace = TRUE))
test_data <- data.frame(cbind(a,b))
test_data$b <- as.factor(test_data$b)

ggplot(test_data, aes(y = a, x = b)) + 
  geom_boxplot()+
  geom_jitter(aes(color = ifelse(a < 5, "red", "black")))

推荐答案

像您一样列出几何图形中的颜色名称并不会告诉色标使用什么颜色,它只是将值分为几类.字符串"red" "black" 不一定有任何含义.如果您想在Geom中分配颜色,请提供您使用的颜色名称或十六进制代码,然后添加 scale_color_identity ,这样就表明"red" 实际上是指使它变成红色",等等.

Listing names of colors in your geom as you did doesn't tell the color scale what colors to use—it just breaks values into categories. The strings "red" or "black" don't necessarily have any meaning there. If you want to assign colors inside a geom, give the color names or hex codes you're using, then add scale_color_identity so there's an indication that "red" actually means "make this have a red color," etc.

library(tidyverse)

ggplot(test_data, aes(y = a, x = b)) +
  geom_boxplot() +
  geom_jitter(aes(color = ifelse(a < 5, "red", "black"))) +
  scale_color_identity()

更好的是(并且更具可伸缩性和可维护性)是关注点的分离:让geoms处理创建几何图形并映射到比例尺,让scales处理比例尺的外观.您可以使用 a<5 作为变量(一种代理变量,因为它不在您的数据框中),将采用true或false值.然后使用诸如 scale_color_manual 之类的色标,根据真值或假值设置颜色.

Better yet (and more scaleable and maintainable) is a separation of concerns: let geoms handle creating geometries and mapping onto scales, and let scales handle setting what scales look like. You can use a < 5 as the variable (kind of a proxy variable, since it isn't in your data frame) which will take on true or false values. Then use a color scale, such as scale_color_manual, to set colors based on true or false values.

ggplot(test_data, aes(y = a, x = b)) +
  geom_boxplot() +
  geom_jitter(aes(color = a < 5)) +
  scale_color_manual(values = c("TRUE" = "red", "FALSE" = "black"))

reprex软件包(v0.2.0)创建于2018-07-03.

Created on 2018-07-03 by the reprex package (v0.2.0).

这篇关于基于值的Geom_jitter颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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