ggpubr在ggdotchart中无法创建多个条形图

7

使用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()
           )

期望输出为: enter image description here

但实际输出为: enter image description here

2个回答

2
这里有一种方法可以获得您想要的绘图而不使用 ggpubr::ggdotchart。问题似乎在于,geom_segment 不允许闪避,正如这里所讨论的: R - ggplot 闪避 geom_lines 如何使 jitter/dodge geom_segments 保持平行?
# your data
df <- diamonds %>%
  filter(color %in% c("J", "D")) %>%
  group_by(cut, color) %>%
  summarise(counts = n())

第一步是扩展您的数据。当我们调用geom_line时,我们将需要这个功能来进行闪躲。我从@Stibu的答案中得到了这个想法。我们创建df的副本,并将df2中的counts列更改为0。最后,我们使用bind_rowsdfdf2创建为单个数据框。
df2 <- df
df2$counts <- 0

df_out <- purrr::bind_rows(df, df2)
df_out

我使用 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()

enter image description here


1
我不知道 geom_segments 不支持躲避,现在一切都说得通了!感谢 @markus - Jenks

1
你需要额外添加一个“group”参数!
    df <- diamonds %>%
  dplyr::filter(color %in% c("J", "D")) %>%
  dplyr::group_by(cut, color) %>%
  dplyr::summarise(counts = n())

ggdotchart(df, x = "cut", y ="counts",
           color = "color", group="color", # here it is
           palette = "jco", size = 3, 
           add = "segment", 
           add.params = list(color = "lightgray", size = 1.5),
           position = position_dodge(0.3),
           ggtheme = theme_pubclean()
)

Fixed plot:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接