[英]ggplot geom_boxplot color and group variables
I'm trying to make a straightforward boxplot in ggplot. 我试图在ggplot中制作一个简单的箱线图。 I'm not sure how get a grouping variable and a color/fill variable. 我不确定如何获得分组变量和颜色/填充变量。 I've tried to gather, but that doesn't seem to work. 我已尝试收集,但这似乎没有用。 Any thoughts? 有什么想法吗?
library(tidyverse)
# Does not work
mtcars %>%
as_tibble() %>%
ggplot(aes(factor(gear),
mpg,
group = vs)) +
geom_boxplot(aes(fill = as.factor(gear)))
# Does not work either
mtcars %>%
as_tibble() %>%
select(gear, mpg, vs) %>%
gather(key, value, -vs) %>%
ggplot(aes(key,
value)) +
geom_boxplot(aes(color = vs))
I'm not sure this is your intended output ( gear
as x-axis and fill
), but here's a working example: 我不确定这是否是您想要的输出( gear
作为x轴和fill
),但这是一个有效的示例:
mtcars %>%
ggplot(
aes(
x = factor(gear),
y = mpg,
color = factor(vs),
fill = factor(gear)
)
) + geom_boxplot()
I've found being explicit when declaring your aesthetic mappings can be helpful when learning ggplot2
. 我发现在声明您的美学映射时应该明确,这对学习ggplot2
。
Alternatively: 或者:
mtcars %>%
as_tibble() %>%
group_by(vs) %>%
ggplot(aes(factor(gear),
mpg,
fill=as.factor(gear))) +
geom_boxplot()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.