Showing data values on stacked bar chart in ggplot2

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

I'd like to show data values on stacked bar chart in ggplot2. Here is my attempted code

Year      

I'd like to show these data values in the middle of each portion. Any help in this regard will be highly appreciated. Thanks

回答1:

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +   geom_bar(stat = "identity") +   geom_text(size = 3, position = position_stack(vjust = 0.5)) 

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2) library(plyr)  # calculate midpoints of bars (simplified using comment by @DWin) Data % #    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))  # plot bars and add text p 



回答2:

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid) library(gridExtra) library(plyr)  # create a new column with proportions prop 

This will give you a 2 panel display like this:

If you want to add Frequency values a table is the best format.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!