r - geom_jitter 的高度/宽度参数与对数刻度交互

标签 r ggplot2

在探索一些数据时遇到这个问题,感觉像是意外行为,所以我想发帖。

geom_jitter 采用高度/宽度参数来表示抖动的宽度,默认值为 40%。当您添加对数刻度时,这 40% 似乎适用于原始值。但是,如果您想调整此参数,该值将在对数转换后应用。

这可以这样说明:

library(ggplot2)
library(patchwork)

set.seed(1)
dat <- data.frame(x=round(rlnorm(2000)), y=round(rlnorm(2000)))


# THESE TWO PLOTS ARE THE SAME
# with jitter
p1 <- ggplot(dat, aes(x,y)) + geom_jitter(alpha=.1) +
  labs(title='regular scale, jitter with default height/width',
       subtitle = '')
# with jitter, and explicit (but same as default) jitter size
p2 <- ggplot(dat, aes(x,y)) + geom_jitter(alpha=.1, height=.4, width=.4) +
  labs(title='regular scale, jitter with 40% height/width',
       subtitle = '<== same as that')


# THESE TWO PLOTS ARE NOT THE SAME
# with jitter and log/log scale
p3 <- ggplot(dat, aes(x,y)) + geom_jitter(alpha=.1) +
  scale_x_log10() + scale_y_log10() +
  labs(title='log scale, jitter with default height/width',
       subtitle = '')

# with jitter and log/log scale, and explicit (but same as default) jitter size
p4 <- ggplot(dat, aes(x,y)) + geom_jitter(alpha=.1, height=.4, width=.4) +
  scale_x_log10() + scale_y_log10()  +
  labs(title='log scale, jitter with 40% height/width',
       subtitle = '<== NOT the same as that')

(p1 + p2) / (p3 + p4)

enter image description here

这是预期的行为吗?

如果我想调整基础值而不是对数转换值的抖动宽度怎么办?

最佳答案

这是一个不错的收获!我想这是一个文档问题——还不够清楚。抖动不是 40%,它是数据分辨率的 40%

ggplot2:::PositionJitter$setup_params 中可以看到应用了 ggplot2:::resolution 函数,其结果乘以 0.4:

list(width = self$width %||% (resolution(data$x, zero = FALSE) * 
    0.4), height = self$height %||% (resolution(data$y, zero = FALSE) * 
    0.4), seed = self$seed)

所以你需要做的是在将值传递给 width/height:

之前应用 ggplot2:::resolution
geom_jitter(
  width = ggplot2:::resolution(log10(dat$x), FALSE) * 0.4,
  height = ggplot2:::resolution(log10(dat$y), FALSE) * 0.4,
)

enter image description here

所有代码:

ggplot(dat, aes(x, y)) + 
  geom_jitter(
    width = ggplot2:::resolution(log10(dat$x), FALSE) * 0.4,
    height = ggplot2:::resolution(log10(dat$y), FALSE) * 0.4,
  ) +
  scale_x_log10() +
  scale_y_log10() +
  labs(title = 'Scale when resolution is applied')

关于r - geom_jitter 的高度/宽度参数与对数刻度交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56013149/

相关文章:

r - emmeans:使标记的意思更大

java - 将 REXP 对象转换为 double 组 (Java/R)

r - 同时使用 formattable 和 plotly

r - 我想弄清楚如何解析网页

r - 当一些图有图例而其他图没有时,在 ggplot2 中对齐多个图

r - 在给定的 x 处添加垂直线段,在两条回归线的截距之间延伸

rgb() 与 R 中的 ggplot2

javascript - Highcharter Shiny 事件 - 将多个选定点返回到数据框

r - 如何从 R 中的特定包中分离所有对象和方法?

r - 我如何写 "*value* *plus-minus sign* *value* ",连同文本,以及 ggplot2,R 的注释?