简体   繁体   English

如何在堆积条形图ggplot2之上组织百分比值

[英]How to organize percentage values on top of a stacked bar chart ggplot2

I have a very skewed bar chart in ggplot2. 我在ggplot2中有一个非常倾斜的条形图。

Here's the dput text output: 这是输出文本输出:

structure(list(Name = structure(c(1L, 3L, 4L, 5L, 6L, 2L, 1L, 
3L, 4L, 5L, 6L, 2L), .Label = c("A", "Average", "B", "C", "D", 
"E"), class = "factor"), variable = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Undiscounted", "Discounted"
), class = "factor"), value = c(18453601.4400001, 11941354.11, 
10748756.04, 6488253.74000001, 6078914.73000002, 2509377.50173653, 
1157538776.56, 833907589.89, 674006380.96, 574466340.26, 534854603.27, 
13191411.5509581)), row.names = c(NA, -12L), .Names = c("Name", 
"variable", "value"), class = "data.frame")

Here's the code I use to plot it: 这是我用来绘制它的代码:

library(ggplot2)
  text_size= 18
  label_bottom_size=18
  plot1<- ggplot(df1, aes(x = Name, y = value, fill = variable)) + 
    geom_bar(stat = "identity")+
    ggtitle(sprintf("Bar chart of Stuff" ))+
    theme(axis.title=element_text(size=text_size))+
    theme(plot.title=element_text(size=text_size+20))+
    theme(axis.text.x= element_text(size=label_bottom_size))+
    theme(axis.text.y= element_text(size=text_size))+
    theme(legend.text = element_text(size=text_size))+
    theme(legend.title = element_text(size=text_size))

As some of the bar charts are so small and text doesn't fit, what I want to do is just have a (X%/Y%) above each bar that shows the percentage breakout. 由于某些条形图非常小且文字不合适,我想要做的只是在每个条形图上方(X%/ Y%)显示百分比突破。 The values shown are in dollars. 显示的值以美元为单位。

Thank you! 谢谢!

This is some hack using data.table for aggregating the data and then displaying it with geom_text (there are probably better ways though) 这是一些hack使用data.table来聚合数据然后用geom_text显示它(虽然可能有更好的方法)

library(data.table)
temp <- data.table(df1)[, per := (value/sum(value))*100, by = Name]
temp <- temp[, list(value = sum(value), 
                    per = paste(sprintf("%.02f%%", per), collapse = " / "),
                    variable = variable), by = Name]

library(ggplot2)
text_size= 18
label_bottom_size=18
ggplot(df1, aes(x = Name, y = value, fill = variable)) + 
  geom_bar(stat = "identity")+
  ggtitle(sprintf("Bar chart of Stuff" ))+
  theme(axis.title=element_text(size=text_size),
  plot.title=element_text(size=text_size+20),
  axis.text.x= element_text(size=label_bottom_size),
  axis.text.y= element_text(size=text_size),
  legend.text = element_text(size=text_size),
  legend.title = element_text(size=text_size)) +
  geom_text(data = temp, aes(x = Name, y = value, label = per), vjust=-0.3)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM