plotting grouped bar charts in R

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

问题:

i am trying to plot this data in R -

column1  column2  column3 1-2       abc       10 1-2       def       15 1-2       ghi       20 2-3       abc       80 2-3       def       95 2-3       ghi       10 3-4       abc       30 3-4       def       55 3-4       ghi       80

the x axis would be column1 (so 1-2, 2-3 and 3-4 would be present as the x axis), and on y axis, the values in column3 should be plotted for each of the column2 elements. So this would be a "grouped" barchart essentially.

I am not able to plot this grouped bar chart using R. The code snippet I am using is below:

dataset 

How do I get this grouped bar chart to display? Thanks!

回答1:

Your problem seem to come down to wrong data formatting. You need to make a matrix with the right row names structure to create plot that you want with base graphics. Here is your solution:

#your data... d 

However, I sometimes like to use lattice for this kind of task. This time you don't even have to make matrix, you just keep your data.frame in original format:

d 



回答2:

I like to use ggplot2 for this kind of task.

#Make the data reproducible: column1 

The reason I find this intuitive (after a bit of a learning period) is that you clearly stated what you want on the x and y axes, and we simply tell ggplot that (as well as which variable defines the 'fill' color, and which kind of plot - here, geom_bar - to use.



回答3:

I found help from Drew Steen's answer, but this code above did not work for me as show above. I added stat="identity" and it works.

require(ggplot2) ggplot(d, aes(x=column1, y=column3, fill=column2)) + geom_bar(stat="identity", position=position_dodge())

Thank you Drew for your answer.



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