问题
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