我在ggplot2中有一个非常倾斜的条形图。
这是输出文本输出:
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")
这是我用来绘制它的代码:
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))
由于某些条形图非常小且文字不合适,我想要做的只是在每个条形图上方(X%/ Y%)显示百分比突破。显示的值以美元为单位。
谢谢!
答案 0 :(得分:5)
这是使用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)