5

利用 中的示例包代码ggpubr,该ggdotchart函数不会像示例中所示创建单独的段,而是只有一个段,尽管点似乎放置在正确的方向上。有人对可能出现的问题有任何提示吗?我认为这可能是由于 tibbles 与 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()
           )

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

但相反,我得到: 在此处输入图像描述

4

2 回答 2

2

这是一种无需ggpubr::ggdotchart. 问题似乎是geom_segment不允许躲避,如此处所述:R - ggplot dodging geom_lines和这里:如何抖动/躲避 geom_segments 使它们保持平行?.

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

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

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

在此处输入图像描述

于 2018-11-14T21:59:43.130 回答
0

您需要一个额外的“组”参数!

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

固定情节:

于 2021-11-01T23:25:28.080 回答