簡體   English   中英

將百分比標簽添加到堆疊條形圖

[英]Add percentage labels to a stacked barplot

我已經成功地在 R 中制作了一個堆疊條形圖,其中幾個不同類別的百分比加起來為 100%。 我在這里制作了一個示例數據框。

example.Category<- c("Cat1","Cat2","Cat3","Cat4","Cat5","Cat6")
percent.good <- c(.25,.29,.45,.5,.8,.82)
example.data <- data.frame(example.Category,percent.good)
example.data$percent.bad <- (1-example.data$percent.good)

數據框看起來像這樣。

     example.Category percent.good percent.bad
1             Cat1         0.25        0.75
2             Cat2         0.29        0.71
3             Cat3         0.45        0.55
4             Cat4         0.50        0.50
5             Cat5         0.80        0.20
6             Cat6         0.82        0.18

然后我使用 reshape 包中的melt來得到這個......

example.melt <- melt(example.data, id.vars="example.Category")

   example.Category     variable value
1              Cat1 percent.good  0.25
2              Cat2 percent.good  0.29
3              Cat3 percent.good  0.45
4              Cat4 percent.good  0.50
5              Cat5 percent.good  0.80
6              Cat6 percent.good  0.82
7              Cat1  percent.bad  0.75
8              Cat2  percent.bad  0.71
9              Cat3  percent.bad  0.55
10             Cat4  percent.bad  0.50
11             Cat5  percent.bad  0.20
12             Cat6  percent.bad  0.18

然后我使用 ggplot 制作了一個顯示這些百分比的堆疊條形圖。

ggplot(example.melt, aes(x=example.Category, y=value, fill = variable)) +
  geom_bar(position = "fill", stat = "identity",color='black',width=0.9) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = paste0((example.data$percent.good && example.data$percent.bad)*100), '%'),position = position_dodge(width = .9),size = 3)

這產生了這個圖,這是我想要的,除了它的標簽方式。 圖

我想要做的是在每個堆疊條上為每種顏色設置百分比標簽,我不知道該怎么做,並且確定我沒有做對。 我設法做的就是以某種方式創建另一個大約有 100 個的類別。 我如何讓百分比標簽出現在這個圖表上,為條形的每個部分顯示?

我希望這不是多余的/之前問過的。 謝謝。

這會給你答案:

ggplot(example.melt, aes(x=example.Category, y=value, fill = variable)) +
  geom_bar(position = "fill", stat = "identity",color='black',width=0.9) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(label = paste0(value*100,"%")), 
            position = position_stack(vjust = 0.5), size = 2)

情節看起來像這樣:

在此處輸入圖片說明

你可以做這樣的事情......

#set positions for labels
example.melt$labelpos <- ifelse(example.melt$variable=="percent.bad",
                         example.melt$value/2, 1 - example.melt$value/2)
ggplot(example.melt, aes(x=example.Category, y=value, fill = variable)) +
  geom_bar(position = "fill", stat = "identity",color='black',width=0.9) +
  scale_y_continuous(labels = scales::percent) +
#use positions to plot labels
  geom_text(aes(label = paste0(100*value,"%"),y=labelpos),size = 3)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM