注释每个组的小节百分比

时间:2019-06-30 19:03:55

标签: r ggplot2 graph bar-chart

我使用ggplot2创建了以下条形图(如果运行代码,您将看到所有内容),但是我希望百分比而不是每个条形顶部的注解是计数(这很容易),但是每年。如果运行以下代码,您将理解我的意思。

例如,我希望在2016年看到会员和临时工的百分比(两者之和为100%)。如果我只写label :: percent等,我将以百分比表示所有年份的总和。

预先感谢

 library(reshape2)
 library(ggplot2)
 library(extrafont)

year = c(2016, 2017, 2018)
members = c(762017, 825130, 865997)
casual = c(275848, 366359, 268330)

df = data.frame(year, members, casual)
dfm <- melt(df, id=c("year"))


ggplot(dfm, aes(x = as.factor(year), y= value, fill = variable)) +
theme_minimal() +
geom_bar(stat="identity", width=.8, colour = 'black', position = "dodge", alpha = 0.8) +
labs(title = "Members vs Casual ", y = 'Percentage', x = "Year") +
geom_text(aes(label=value), position=position_dodge(width=0.9), vjust=-0.25)+
scale_fill_manual(values=c("dodgerblue2", "red3")) +
theme(plot.title = element_text(size=17, family = 'Times New Roman', color = "black", face = 'bold')) +
theme(plot.caption = element_text(size = 8, family = 'Times New Roman')) +
theme(plot.subtitle = element_text(size=13, family = 'Times New Roman', color = "black", face = 'bold')) +
theme(axis.text.y = element_text(size = 11, family = 'Times New Roman', color = "black")) +
theme(axis.text.x = element_text(hjust = 1, size = 11, family = 'Times New Roman', color = "black")) +
theme(axis.title.y = element_text(size = 14, family = 'Times New Roman', color = "black", face = 'bold')) +
theme(axis.title.x = element_text(size = 14, family = 'Times New Roman', color = "black", face = 'bold')) +
scale_y_continuous(breaks=seq(0, 900000, 100000)) +
theme(panel.background = element_rect(colour = "gray30", size = 0.5, linetype = "solid") )+
theme(panel.grid.minor = element_blank()) +
theme(panel.grid.major.x = element_blank()) +
theme(legend.title=element_blank()) + 
theme(legend.position="bottom") +
theme(legend.key.size = unit(0.6, "cm")) +
theme(legend.text=element_text(size=9), legend.spacing.x = unit(0.4, 'cm') ) +
theme(legend.background = element_rect(fill="gray90", size=0.1, linetype="solid")) 

1 个答案:

答案 0 :(得分:1)

您可以在sed 's:</p>:\n:g; s/MYSTART[^\n]*\n/RESULTAFTERSUBSTITUTIONWORKS/; s:\n:</p>:g' 行中计算百分比:

dfm

然后将dfm <- melt(df, id = c("year")) %>% group_by(year) %>% mutate(value = value/sum(value))添加到您的scales::percent

geom_text