ggplot2:为每个条形注释带有总计的堆积条形

时间:2022-06-15 15:02:21

I would like to annotate a plot so as to show the totals for each column. For example

我想注释一个图,以显示每列的总数。例如

 ggplot(diamonds, aes(clarity, fill=cut)) + 
        geom_bar(position="fill") +
        scale_y_continuous(name="proportion")

This will produce a stacked barplot. However it is difficult to know what is n for each of the bars. I1,SI2 and so on. How can I annotate it so that, for each bar, n is displayed at the top?

这将产生堆叠的条形图。然而,很难知道每个条的n是多少。 I1,SI2等。如何对其进行注释,以便对于每个条形图,n显示在顶部?

1 个解决方案

#1


3  

The easiest way is to compute the totals before plotting, then adding them to the plot separately. First, we calculate columns totals:

最简单的方法是在绘图之前计算总计,然后将它们分别添加到绘图中。首先,我们计算列总数:

totals = tapply(diamonds$price, diamonds$clarity, length)
dd = data.frame(clarity = names(totals), labels = as.vector(totals), y= 1)

Then we use geom_text to add the totals:

然后我们使用geom_text添加总计:

ggplot(diamonds, aes(clarity)) + 
    geom_bar(aes( fill=cut), position="fill") +
    scale_y_continuous(name="proportion") + 
    geom_text(data=dd, aes(x=clarity, y=y, label=labels), size=4)

#1


3  

The easiest way is to compute the totals before plotting, then adding them to the plot separately. First, we calculate columns totals:

最简单的方法是在绘图之前计算总计,然后将它们分别添加到绘图中。首先,我们计算列总数:

totals = tapply(diamonds$price, diamonds$clarity, length)
dd = data.frame(clarity = names(totals), labels = as.vector(totals), y= 1)

Then we use geom_text to add the totals:

然后我们使用geom_text添加总计:

ggplot(diamonds, aes(clarity)) + 
    geom_bar(aes( fill=cut), position="fill") +
    scale_y_continuous(name="proportion") + 
    geom_text(data=dd, aes(x=clarity, y=y, label=labels), size=4)