Stacked barchart

别说谁变了你拦得住时间么 提交于 2020-02-07 03:40:42

问题


I'm having a really hard time trying to figure out how to make a stacked bar chart in R.

First of all, the data I'm working with is from the VCD package

data("Arthritis", package = "vcd")

Now, I only want to graph the columns Improved and Treatment, displaying two bars which are the two results of the Treatment column (Treated, Placebo) and have the results of the Improved column stacked on top of each other.

I tried some commands but it kept giving me an error saying:

'height' must be a vector or a matrix

So I did the following, but it gave me all the results for all the columns in the Arthritis dataset.

arth <- as.matrix(Arthritis)
barplot(arth,
        main="Improvements in Treated vs Placebo",
        col=c("green","yellow", "blue"),
        xlab="Treatment",
        ylab="Frequency")

I have no idea what to try anymore. Any help or guidance would be amazing.


回答1:


Couple of things wrong with your approach. I think you want something like this:

barplot(xtabs(~ Improved + Treatment, data = Arthritis))



回答2:


You may also try ggplot. The data should be in a data.frame (no need to convert to matrix). Default geom_bar counts the number of cases in each group (no need to tabulate).

library(ggplot2)
ggplot(data = Arthritis, aes(x = Treatment, fill = Improved)) +
  geom_bar() +
  scale_fill_manual(values = c("green","yellow", "blue")) +
  ggtitle("Improvements in Treated vs Placebo") +
  xlab("Treatment") +
  ylab("Frequency")



来源:https://stackoverflow.com/questions/19553605/stacked-barchart

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