[英]How can you add percentage labels to a factor based pie chart in ggplot2
我對ggplot相當陌生,所以這可能是一個非常簡單的問題,但我無法解決。 我使用ggplot根據數據幀中的因子變量構建餅圖。 變量級別為“ F”和“ M”。
hcgen <- ggplot(hc, aes(x = factor(1), fill = gender))
然后我用一個空白的主題形象化圖表
hcgen + geom_bar(width = 1) + coord_polar("y") + blank_theme + theme(axis.text.x=element_blank())
我使用了不同的選項來添加標簽,但沒有任何效果。 我用例如:
geom_text(aes(y = value/3 + c(0, cumsum(value)[-length(value)]), + label = percent(value/100)), size=5)
但這給出了以下錯誤
Error in FUN(X[[i]], ...) : object 'value' not found
我究竟做錯了什么?
看起來您正在將代碼復制和粘貼到您不知道數據的地方,在這種情況下,您正在使用的代碼是這樣的:
library(ggplot2)
library(scales)
df <- data.frame(
group = c("Male", "Female", "Child"),
value = c(25, 25, 50))
bp <- ggplot(df, aes(x="", y=value, fill=group))+
geom_bar(width = 1, stat = "identity")
pie <- bp + coord_polar("y", start=0)
blank_theme <- theme_minimal()+
theme(
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.border = element_blank(),
panel.grid=element_blank(),
axis.ticks = element_blank(),
plot.title=element_text(size=14, face="bold")
)
pie + scale_fill_brewer("Blues") + blank_theme +
theme(axis.text.x=element_blank())+
geom_text(aes(y = value/3 + c(0, cumsum(value)[-length(value)]),
label = percent(value/100)), size=5)
添加dplyr和一些ggplot2更新當然可以簡化它:
library(dplyr)
library(ggplot2)
library(scales)
df <- data.frame(
group = c("Male", "Female", "Child"),
value = c(25, 25, 50))
df %>%
ggplot(aes(x="", y=value, fill=group)) +
geom_col() +
geom_text(aes(label = percent(value/100)), position = position_stack(vjust = 0.5)) +
scale_fill_brewer(palette = "Blues") +
coord_polar("y") +
theme_void() +
labs(title = "TITLE",
fill = "LEGEND")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.