如何添加线以在散点图中的各个饼之间进行连接?

时间:2020-07-24 09:45:18

标签: r ggplot2 scatterpie

我有一个散布图,在x和y轴上绘制了饼图。如何添加连接馅饼之间的直线?理想情况下,我希望这些线连接位于馅饼中心点下方的y值。

我尝试添加geom_path,但没有成功。

此问题是我之前发布的this问题的后续内容。

我的数据

library(tidyverse)
library(scatterpie)

my_df <- structure(list(day_in_july = 13:20, yes_and_yes = c(0.611814345991561, 
0.574750830564784, 0.593323216995448, 0.610539845758355, 0.650602409638554, 
0.57429718875502, 0.575971731448763, 0.545454545454545), yes_but_no = c(0.388185654008439, 
0.425249169435216, 0.406676783004552, 0.389460154241645, 0.349397590361446, 
0.42570281124498, 0.424028268551237, 0.454545454545455), y = c(0.388185654008439, 
0.425249169435216, 0.406676783004552, 0.389460154241645, 0.349397590361446, 
0.42570281124498, 0.424028268551237, 0.454545454545455)), row.names = c(NA, 
-8L), class = c("tbl_df", "tbl", "data.frame"))



我当前的散布图


p <- ggplot(data = my_df) +
  geom_scatterpie(aes(x = day_in_july, y = y*50, r = 0.3), 
                  data = my_df, 
                  cols = colnames(my_df)[2:3],
                  color = "red") + 
  geom_text(aes(y = y*50, x = day_in_july, 
                label = paste0(formatC(y*100, digits = 3), "%")),
            nudge_y = 0.07, nudge_x = -0.25, size = 3) +
  geom_text(aes(y = y*50, x = day_in_july, 
            label = paste0(formatC((1-y)*100, digits = 3), "%")),
            nudge_y = -0.07, nudge_x = 0.25, size = 3) +
  scale_fill_manual(values = c("pink", "seagreen3")) +
  scale_x_continuous(labels = xvals, breaks = xvals) +
  scale_y_continuous(name = "yes but no",
                     labels = function(x) x/50) + 
  coord_fixed()

> p

scatterpie



我想连接这些饼以表示一段时间内的趋势,例如:

scatterpie_connected

  • 基本上,我想将每个饼图后面的y值连接起来,以使该线位于馅饼后面。

  • 我尝试添加geom_path()。但这没有用,我只是得到了同一条情节而没有任何线条。还尝试了geom_line,但没有成功。

p + geom_path(x = as.numeric(my_df$day_in_july), y = my_df$yes_but_no)

1 个答案:

答案 0 :(得分:1)

只需在代码的开头添加geom_pathxy相同的美感

p <- ggplot(data = my_df) +
  geom_path(aes(x = day_in_july, y = y*50)) +
  geom_scatterpie(aes(x = day_in_july, y = y*50, r = 0.3), 
                  data = my_df, 
                  cols = colnames(my_df)[2:3],
                  color = "red") + 
  geom_text(aes(y = y*50, x = day_in_july, 
                label = paste0(formatC(y*100, digits = 3), "%")),
            nudge_y = 0.07, nudge_x = -0.25, size = 3) +
  geom_text(aes(y = y*50, x = day_in_july, 
                label = paste0(formatC((1-y)*100, digits = 3), "%")),
            nudge_y = -0.07, nudge_x = 0.25, size = 3) +
  scale_fill_manual(values = c("pink", "seagreen3")) +
  # scale_x_continuous(labels = xvals, breaks = xvals) +
  scale_y_continuous(name = "yes but no",
                     labels = function(x) x/50) + 
  coord_fixed()

enter image description here