ggplot、facet、饼图、缺失值

这是我的最终数据集。我最初通过单独计算值并在原始较大数据集的女性 (F) 和男性 (M) 之间进行 rbind 获得此表。

我正在尝试制作一个漂亮的饼图,外面有百分比标签,我遇到了所有可能的问题,但我找不到解决方案。 请注意,数据框中的男性没有值 A。

数据框: sex ms n_ms n msPerc 值 1 F A 1 91 0.01098901 1.098901 2 FB 18 91 0.19780220 19.780220 3 F C 65 91 0.71428571 71.428571 4 F D 7 91 0.07692308 7.692308 5 MB 11 108 0.10185185 10.185185 6 M C 86 108 0.79629630 79.629630 7 MD 11 108 0.10185185 10.185185

library(ggplot2)
library(ggrepel)
library(tidyverse)

n<- c(91,91,108,108 )
n_ms<-c(1,18,65,7,11,86,11)
sex<- c("F","F","M"," M","M")
ms<- c("A","B","C","D","D")

df <- data.frame(sex,ms,n_ms,n)
df[is.na(df)]<- 0
df$msPerc <- df$n_ms /df$n 
df$value <- 100*df$n_ms /df$n
df$n_ms<- as.integer(df$n_ms) # original big dataframe (doing for replication purposes)
df$n<- as.integer(df$n)

#creating position of labels
df2 <- df %>% 
  mutate(csum = rev(cumsum(rev(value))),pos = value/2 + lead(csum,1),pos = if_else(is.na(pos),value/2,pos))


ms_pie<-ggplot(df,aes(x="",y=msPerc,group=sex,fill=ms)) +
  geom_bar(width = 1,stat = "identity") +
  coord_polar("y",start=0) + 
  facet_grid(.~ sex) +
  theme_void()+
  theme(legend.position="top",legend.text = element_text(size = 9),legend.title = element_text(size = 9,face = "bold"))+
  scale_fill_manual(values=c("#d7191c","#fdae61","#abd9e9","#5e3c99"),name="Moulting stage",labels=c("A","D"))+
#  geom_label(aes(label = percent(msPerc)),#             position = position_stack(vjust = 0.5),#             show.legend = FALSE)
# geom_text(aes(label = percent(msPerc)),size = 3,color = "black",#           position = position_stack(vjust = 0.5),#           show.legend = FALSE)
 geom_label_repel(data = df2,aes(y = pos,label = paste0(value,"%")),size = 4.5,nudge_x = 1,show.legend = FALSE)

ms_pie

这是怎么回事...

ggplot、facet、饼图、缺失值

我想要的是来自 https://r-charts.com/part-whole/pie-chart-labels-outside-ggplot2/ 的饼图,但在变量“sex”中包含 facet_grid。

ggplot、facet、饼图、缺失值

ggplot、facet、饼图、缺失值

到目前为止,这是我得到的最接近的。使用 geom_label,但是我的值重叠,我也不知道如何将它们分开......成为 R 初学者的乐趣。

我也尝试了 ggplot,facet,piechart: placing text in the middle of pie chart slices 中提供的解决方案,但 coor_polar 不适用于“免费”秤。

非常感谢您的帮助。 亲切的问候。

chenyuhui22 回答:ggplot、facet、饼图、缺失值

我试图清理您的代码有几个问题(请参阅 yourArray.map(obj => ({key:"id,name,desc",value:`${obj.id},${obj.name},${obj.desc}`})) 前面的注释)- 这应该能让您更接近:

####
本文链接:https://www.f2er.com/10767.html

大家都在问