【发布时间】:2019-06-30 19:03:55
【问题描述】:
我使用 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"))
【问题讨论】: