0
votes

I am hoping to make a stacked bar plot to show two factors. The questions and answers I can find on this site that address this problem all work with data that appears to be in a matrix format and use ggplot2. My data is in lists of observations, like this:

mydata = data.frame(V1=c("A","B","B","C","C"), V2=c("X","X","Y","Z","Z"))

I would like to show categories of V1 on the x axis of my plot, but stacked to show the proportions of V2 in each bar.

I can use the "count" function in the plyr library to find the frequency of each observation,

library(plyr)
mydata.count = count(mydata)

but I don't know how to structure my barplot command to group data by the level of V1: barplot(mydata.count$freq) separates all combinations of V1 and V2 into separate bars.

If possible, I would like to create this plot using the base R barplot functions so that it is visually consistent with other plots in my study.

1
barplot(t(table(mydata))) - d.b
@d.b, thank you, that is exactly what I needed. Do you know how to determine how colors are assigned to factor levels? - AP Geoscience
barplot(t(table(mydata)), col = c("cyan","darkred","navy"), legend.text = c("X","Y","Z")) colors are already assigned but barplot uses a gamma-corrected grey palette for colors as out input (i.e. t(table(mydata))) is a matrix. - M--

1 Answers

0
votes

Here is another possibility with ggplot:

ggplot(as.data.frame(table(mydata)), aes(x=V1, y=Freq, fill=V2)) + geom_bar(stat="identity")

enter image description here

ggplot(as.data.frame(table(mydata)), aes(x=V2, y=Freq, fill=V1)) + geom_bar(stat="identity")

enter image description here