[英]R ggplot: facet_grid and dodge points
我想在 facet_grid 之后创建一个躲闪的geom_point
facet_grid
。 但我希望我的 plot 只能在 x 轴上躲避! 看起来position_dodge()
沿 y 轴和 x 轴躲避点!
如何控制可以沿哪个轴进行闪避:
我的数据类似于以下内容:
carat cut color clarity depth table price x y z grade
<dbl> <ord> <ord> <ord> <dbl> <dbl> <int> <dbl> <dbl> <dbl> <chr>
1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43 low-quality
2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31 High-quality
3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31 low-quality
4 0.29 Premium I VS2 62.4 58 334 4.2 4.23 2.63 High-quality
5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75 low-quality
6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48 High-quality
...
我的代码如下:
dmnd_data <- diamonds %>% head(100) %>% mutate(grade = ifelse(cut == "Premium", "High-quality", ifelse(cut == "Very Good", "High-quality", "low-quality"))
dmnd_data %>% ggplot(aes(color, cut, size = price)) +
geom_point(alpha = 0.7, position = position_dodge2(width = 0.5)) +
facet_grid(grade~., space = "free", scales = "free")
正如您在下面的 plot 中看到的那样,每个 x 坐标的点都不是居中的,它们在每个网格内的两个轴上都被避开了! 有没有办法控制点在每个facet_grid
中仅沿 x 轴躲避?
position_nudge()
在这里完成你想要的吗?
library(tidyverse)
dmnd_data <- diamonds %>%
head(100) %>%
mutate(
grade = ifelse(
cut == "Premium",
"High-quality",
ifelse(cut == "Very Good", "High-quality", "low-quality")
))
dmnd_data %>% ggplot(aes(color, cut, size = price)) +
geom_point(alpha = 0.7, position = position_nudge(x = 0.5)) +
facet_grid(grade ~ ., space = "free", scales = "free")
由代表 package (v0.3.0) 于 2021 年 12 月 6 日创建
在我看来,闪避效果很好,因为每种颜色的点都被闪避了。 但是,如果我理解正确,您希望针对color
和cut
的每个组合分别躲避点。 不确定这是否可以通过position_dodge
或......但在一些数据争论和切换到连续规模的帮助下,您可以做到:
library(ggplot2)
library(dplyr)
dmnd_data <- diamonds %>%
mutate(grade = ifelse(cut == "Premium", "High-quality", ifelse(cut == "Very Good", "High-quality", "low-quality"))) %>%
head(100)
width <- .5
dmnd_data <- dmnd_data %>%
select(cut, color, grade, price) %>%
group_by(grade, cut, color) %>%
mutate(nudge = if (n() > 1) seq(-width/2, width/2, length.out = n()) else 0) %>%
ungroup()
color_lvls <- levels(dmnd_data$color)
ggplot(dmnd_data, aes(color, cut, size = price)) +
geom_point(aes(as.numeric(color) + nudge), alpha = 0.7) +
scale_x_continuous(breaks = seq_along(color_lvls), labels = color_lvls) +
facet_grid(grade ~ ., space = "free", scales = "free")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.