将 geom_point() 放在躲避条的中间

问题描述 投票:0回答:1

我正在尝试使用

geom_point()
在由
geom_col()
创建的两个躲避条的中间绘制点。

但是这些条被躲避,并且需要位于组标签的右侧,这就是我使用的原因

just = 0
geom_col()
。此外,我想使用
position_dodge2()
所以条之间没有填充。我知道这可以通过
position_dodge()
来完成(参见 here),但这种方法无法使躲避的条形位于刻度线的右侧。

如何为

geom_point()
提供
position_dodge2()
使用的那些条形中间的 x 轴位置?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)

penguins_df <- tibble::tibble(
  island = factor(rep(c("Biscoe", "Dream", "Torgersen"), each = 3L)),
  name = rep(c("bill_length_mm", "bill_depth_mm", "flipper_length_mm"), 3),
  value = c(
    45.25748502994012, 15.874850299401198, 209.70658682634732, 44.16774193548387,
    18.344354838709677, 193.07258064516128, 38.950980392156865,
    18.429411764705883, 191.19607843137254
  ),
)


p <- ggplot(
  data = penguins_df,
  aes(
    x = island,
    y = value,
    group = name,
    fill = name,
    color = name
  )
) +
  geom_col(
    data = ~ filter(.x, name != "flipper_length_mm"),
    # Place columns to right of date breaks
    just = 0,
    position = position_dodge2(padding = 0)
  )

p +
  geom_point(
    data = ~ filter(.x, name == "flipper_length_mm"),
    position = position_dodge2()
  )
#> Warning: Width not defined. Set with `position_dodge2(width = ...)`

创建于 2024-05-22,使用 reprex v2.1.0

r ggplot2 charts
1个回答
0
投票

做到这一点的一种方法是在最后一个学期调整

x
美学......

p +
  geom_point(
    data = ~ filter(.x, name == "flipper_length_mm"),
    aes(x = as.numeric(island) + 0.45),  #0.45 works for default bar spacing
    position = position_dodge2()
  )

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.