如何在同一个图中将position_dodge应用于geom_point和geom_text?

时间:2018-05-05 02:25:04

标签: r ggplot2

我希望能够在应用position_dodge时使geom_point内的geom_text跟随重新定位。也就是说,我想从以下代码中获取:

Q <- as_tibble(data.frame(series = rep(c("diax","diay"),3),
                          value = c(3.25,3.30,3.31,3.36,3.38,3.42),
                          year = c(2018,2018,2019,2019,2020,2020))) %>%
  select(year, series, value)

ggplot(data = Q, mapping = aes(x = year, y = value, color = series, label = sprintf("%.2f",value))) +
  geom_point(size = 13) +
  geom_text(vjust = 0.4,color = "white", size = 4, fontface = "bold", show.legend = FALSE) 

产生以下图表:

enter image description here

进行以下更改:

ggplot(data = Q, mapping = aes(x = year, y = value, color = series, label = sprintf("%.2f",value))) +
  geom_point(size = 13, position = position_dodge(width = 1)) +
  geom_text(position = position_dodge(width = 1), vjust = 0.4,
            color = "white", size = 4, fontface = "bold",
            show.legend = FALSE)

产生以下图表:

enter image description here

关于这一点的奇怪之处在于,如果我从geom_point更改为geom_bar,那么同样的变化就可以正常运行:

ggplot(Q, aes(year, value, fill = factor(series), label = sprintf("%.2f",value))) +
  geom_bar(stat = "identity", position = position_dodge(width = 1)) + 
  geom_text(color = "black", size = 4,fontface= "bold",
            position = position_dodge(width = 1), vjust = 0.4, show.legend = FALSE) 

2 个答案:

答案 0 :(得分:3)

这是因为躲避是基于group美学,在这种情况下自动设置为series,因为它映射到颜色。问题是文本层有自己的颜色("white"),因此分组被删除。手动设置分组,一切都很好:

ggplot(Q, aes(x = year, y = value, color = series, label = sprintf("%.2f",value), group = series)) +
    geom_point(size = 13, position = position_dodge(width = 1)) +
    geom_text(position = position_dodge(width = 1), vjust = 0.4, color = "white", size = 4, 
              fontface = "bold", show.legend = FALSE)

enter image description here

答案 1 :(得分:-1)

一个补丁工作如下。由于您无法立即使用geom_text()在数据点顶部添加标签,因此您可能需要稍微调整一下。我首先使用geom_point()创建了一个临时图形。然后,我访问了用于绘制图形的数据框。您可以找到x和y轴的值。使用它们,我创建了一个名为temp的新数据框,其中包括轴信息和标签信息。获得此数据框后,我可以使用temp绘制预期结果。由于您正在使用其他数据框,请确保在inherit.aes = FALSE中使用geom_text()

library(dplyr)
library(ggplot2)

g <- ggplot(data = Q, aes(x = year, y = value, color = series)) +
     geom_point(size = 13, position = position_dodge(width = 1))

temp <- as.data.frame(ggplot_build(g)$data) %>%
        select(x, y) %>%
        arrange(x) %>%
        mutate(label = sprintf("%.2f",Q$value))

ggplot(data = Q, aes(x = year, y = value, color = series)) +
geom_point(size = 13, position = position_dodge(width = 1)) +
geom_text(data = temp, aes(x = x, y = y, label = label), 
          color = "white", inherit.aes = FALSE)

enter image description here