无法在 R 中绘制同心饼图

Can't draw a concentric pie chart in R

我有以下数据:

Phyla       V4         Fl
 <chr>     <dbl>      <dbl>

Proteobacteria  88.58    81.43  
Firmicutes  7.33    15.34   
Actinobacteriota    1.55    1.94        
Bacteroidota    2.20    1.25    

我想使用同心饼图显示数据。我有几个试验:

mycols <- c("#eee0b1", "#da8a67", "#e63e62", "#0033aa")
ggplot(df, aes(x = 2, y = V4, fill = Phyla)) +
  geom_bar(stat = "identity", color = "white") +
  coord_polar(theta = "y", start = 0)+
  geom_text(aes(y = Fl, label = V4), color = "white")+
  scale_y_continuous(breaks=min(df$Fl):max(df$Fl)) +
  scale_fill_manual(values = mycols) +
  theme_void()+
  xlim(0.5, 2.5)

这生成

所以,我只显示了一列。

另一个试验使用了这个:

pie(x=c(88.58,7.33,1.55,2.2),labels="",
col=c("#eee0b1", "#da8a67", "#e63e62", "#0033aa"))
par(new=TRUE)
pie(x=c(81.43,15.34,1.94, 1.25),labels=c("Proteobacteria","Firmicutes","Actinobacteriota", "Bacteroidota"),radius=.5,
    col=c("#eee0b1", "#da8a67", "#e63e62", "#0033aa"))

生成此图:

我不知道哪个更容易修复生成同心饼。我需要包括颜色图例并用类别名称 (V4, Fl) 标记每个饼图,并添加百分比值。

你可以试试这个

df %>%
    pivot_longer(-Phyla, names_to = "type", values_to = "y") %>%
    ggplot(aes(x = type, y = y)) +
    geom_bar(aes(fill = Phyla), stat = "identity",
      color = "white", position = "fill", width=0.7) +
    coord_polar(theta = "y", start = pi/2) +
    geom_text(aes(y = y, group = Phyla, label = y),
      color = "white", position = position_fill(vjust=0.5)) +
    geom_text(aes(x = x, y = y, label = type),
      data = data.frame(x = c(2.5, 3.5), y = c(0, 0), type = c("V4", "Fl"))
    ) +
    scale_fill_manual(values = mycols) +
    scale_x_discrete(limits = c(NA, "V4", "Fl")) +
    theme_void()
  • pivot_longer 将您的数据从“宽”转换为“长”,以便您可以绘制多列。
  • position="fill" in geom_bar()position_fill in geom_text() 会将 y 值缩放为 [0,1],以便两列对齐。
  • vjust=0.5 in position_fill 将显示相应区域的值。
  • 直接使用 x 轴文本标记圆有点困难,但您可以使用 geom_text() 和新的 data.frame(x=c(2.5,3.5),y=c(0,0),type=c("V4","Fl"))
  • 手动标记它们