R ggplot:facet_grid 和闪避点

R ggplot: facet_grid and dodge points

我想在 facet_grid 之后创建一个闪避 geom_point 情节。但我希望我的情节只在 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
...

我的代码如下:

library(ggplot2)
library(dplyr)
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_dodge2(width = 0.5)) + 
   facet_grid(grade~., space = "free", scales = "free")

正如您在下图中看到的那样,每个 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")

reprex package (v0.3.0)

创建于 2021-12-06

在我看来,随着每种颜色的点被闪避,闪避效果很好。但是,如果我理解正确的话,您希望针对 colorcut 的每个组合分别躲避这些点。不确定这是否可以通过 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")