如何使用ggplot2移动饼图中的箭头?

问题描述 投票:0回答:1

我有一些数据想绘制成饼图。我正在使用

ggplot2
,虽然我设法获得了绘图,但我在箭头的位置方面遇到了一些问题,因为它们一起出现在同一方向。

Fig1

是否有可能移动箭头并避免它们在一起,或者是由于数据造成的?

这是一个可重现的示例:

df_count <- structure(list(Expression = structure(1:3, levels = c("DOWN", 
                                                      "NS", "UP"), class = "factor"), NumGenes = c(425L, 55623L, 1138L
                                                      )), class = "data.frame", row.names = c(NA, -3L))
df_count_per <- structure(list(Expression = structure(3:1, levels = c("DOWN", 
                                                      "NS", "UP"), class = "factor"), NumGenes = c(1138L, 55623L, 425L
                                                      ), prop = c(1.99, 97.27, 0.74), ypos = c(0.995, 50.625, 99.63
                                                      )), class = "data.frame", row.names = c(NA, -3L))


library(ggplot2)
library(dplyr)
library(ggrepel)
library(forcats)

ggplot(df_count, aes(x="", y=NumGenes, fill = fct_inorder(Expression))) +
  geom_col(width=1.5, color="black") +
  coord_polar("y", start=0) +
  scale_fill_brewer(palette="Set2")+
  geom_label_repel(data = df_count_per,
                   aes(y = ypos, label = paste0(prop, "%")),
                   size = 4.5, nudge_x = 1, show.legend = FALSE) +
  guides(fill = guide_legend(title = "Expression"))+
  theme_void()

这就是我期望拥有的(或类似的东西):

fig2

任何帮助将不胜感激。

提前非常感谢

r ggplot2 pie-chart
1个回答
0
投票

问题是您设置的

y_pos
ition 是基于比例而不是您用于
geom_col
的计数。

library(ggplot2)
library(dplyr, warn = FALSE)
library(ggrepel)
library(forcats)

df_count_per <- df_count_per |>
  mutate(
    ypos = cumsum(NumGenes),
    ypos = .5 * (ypos + lag(ypos, default = 0))
  )

ggplot(
  df_count,
  aes(x = "", y = NumGenes, fill = fct_inorder(Expression))
) +
  geom_col(width = 1.5, color = "black") +
  coord_polar("y", start = 0) +
  scale_fill_brewer(palette = "Set2") +
  geom_label_repel(
    data = df_count_per,
    aes(y = ypos, label = paste0(prop, "%")),
    size = 4.5, nudge_x = 1, show.legend = FALSE,
  ) +
  guides(fill = guide_legend(title = "Expression")) +
  theme_void()

© www.soinside.com 2019 - 2024. All rights reserved.