【发布时间】:2016-04-26 11:53:05
【问题描述】:
我正在尝试使用ggplot2 绘制漂亮的stacked percent barchart。我已经阅读了一些材料并且几乎设法绘制出我想要的东西。另外,我附上材料,它可能在一个地方有用:
How do I label a stacked bar chart in ggplot2 without creating a summary data frame?
Create stacked barplot where each stack is scaled to sum to 100%
R stacked percentage bar plot with percentage of binary factor and labels (with ggplot)
我的问题是我无法将labels 放置在我想要的位置 - 在栏的中间。
您可以在上图中看到问题 - 标签看起来很糟糕,而且还相互重叠。
我现在正在寻找的是:
如何在条(区域)中间放置标签
如何绘制不是所有标签,但例如大于 10% 的标签?
如何解决重叠问题?
对于Q 1. @MikeWise 建议可能的solution。但是,我仍然无法处理这个问题。
另外,我附上了可重现的例子,我是如何绘制这张图的。
library('plyr')
library('ggplot2')
library('scales')
set.seed(1992)
n=68
Category <- sample(c("Black", "Red", "Blue", "Cyna", "Purple"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:5, n, replace = TRUE, prob = NULL))
USD <- abs(rnorm(n))*100
df <- data.frame(Category, Brand, USD)
# Calculate the percentages
df = ddply(df, .(Brand), transform, percent = USD/sum(USD) * 100)
# Format the labels and calculate their positions
df = ddply(df, .(Brand), transform, pos = (cumsum(USD) - 0.5 * USD))
#create nice labes
df$label = paste0(sprintf("%.0f", df$percent), "%")
ggplot(df, aes(x=reorder(Brand,USD,
function(x)+sum(x)), y=percent, fill=Category))+
geom_bar(position = "fill", stat='identity', width = .7)+
geom_text(aes(label=label, ymax=100, ymin=0), vjust=0, hjust=0,color = "white", position=position_fill())+
coord_flip()+
scale_y_continuous(labels = percent_format())+
ylab("")+
xlab("")
【问题讨论】:
标签: r ggplot2 bar-chart labels