ggpubr 未在 ggdotchart 中创建多个条形图

Jen*_*nks 7 r ggplot2 ggpubr

利用 中的示例包代码ggpubr,该ggdotchart函数不会创建单独的段,如示例中所示,而是只有一个段,尽管点似乎放置在正确的方向。有谁对可能出现的问题有任何提示吗?我认为这可能是由于 tibbles vs. df 等因素造成的,但我一直无法确定问题所在。

代码:

df <- diamonds %>%
  filter(color %in% c("J", "D")) %>%
  group_by(cut, color) %>%
  summarise(counts = n()) 

ggdotchart(df, x = "cut", y ="counts",
           color = "color", palette = "jco", size = 3, 
           add = "segment", 
           add.params = list(color = "lightgray", size = 1.5),
           position = position_dodge(0.3),
           ggtheme = theme_pubclean()
           )
Run Code Online (Sandbox Code Playgroud)

预期输出为: 在此输入图像描述

但我得到的是: 在此输入图像描述

mar*_*kus 2

这是一种无需 . 即可获得所需绘图的方法ggpubr::ggdotchart。问题似乎是geom_segment不允许躲避,如此处讨论的:R - ggplot dodging geom_lines和这里:how to jitter/dodge geom_segments so they keep parallel?

# your data
df <- diamonds %>%
  filter(color %in% c("J", "D")) %>%
  group_by(cut, color) %>%
  summarise(counts = n())
Run Code Online (Sandbox Code Playgroud)

第一步是扩展您的数据。当我们打电话时我们需要这个geom_line来躲避。我从@Stibu 的回答中得到了这个想法。我们创建 的副本df并将该counts列更改0df2。最后,我们使用和bind_rows创建单个数据框。dfdf2

df2 <- df
df2$counts <- 0

df_out <- purrr::bind_rows(df, df2)
df_out
Run Code Online (Sandbox Code Playgroud)

然后我用来ggplot创建/复制您想要的输出。

ggplot(df_out, aes(x = cut, y = counts)) +
  geom_line(
    aes(col = color), # needed for dodging, we'll later change colors to "lightgrey"
    position = position_dodge(width = 0.3),
    show.legend = FALSE,
    size = 1.5
  ) +
  geom_point(
    aes(fill = color),
    data = subset(df_out, counts > 0),
    col = "transparent",
    shape = 21,
    size = 3,
    position = position_dodge(width = 0.3)
  ) +
  scale_color_manual(values = c("lightgray", "lightgray")) + #change line colors
  ggpubr::fill_palette(palette = "jco") +
  ggpubr::theme_pubclean()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述