Reputation: 129
I can not figure out how to get this side by side barplot to display the way I want it to. I am trying to create a side-by-side bar graph showing the nausea (Yes vs No) on the horizontal axis and color-coded bars to indicate the type of anesthetic. I have the plots side by side but the colors represent the yes or no for nausea, not the anesthesia but the legend says they represent the anesthesia. Here is my data:
Nausea_Y Nausea_N
Anesthesia_A 26 13
Anesthesia_B 10 23
and here is my code:
plotdata=data.frame(Anesthesia_Type=c("Anesthesia A","Anesthesia B"),
Anesthesia_A=c(anes_df$Nausea_Y[1],anes_df$Nausea_N[1]),
Anesthesia_B=c(anes_df$Nausea_Y[2],anes_df$Nausea_N[2]),
row.names = c("st1","st2"))
plotdata
d = melt(plotdata, id.vars = "Anesthesia_Type")
ggplot(data = d,
mapping = aes(x = Anesthesia_Type, y = value, fill = variable)) +
geom_col(position = position_dodge())
Any help is appreciated. I know I have it backwards somehow but can't figure out how to change it.
Upvotes: 2
Views: 53
Reputation: 34601
Assuming the data is starting as a table as presented above (that the anesthetic is a row name and not an explicit variable):
dat <- read.table(text = "Nausea_Y Nausea_N
Anesthesia_A 26 13
Anesthesia_B 10 23", header = TRUE)
# Reshape to long format
plotdata <- as.data.frame.table(as.matrix(dat))
library(ggplot2)
ggplot(plotdata,
mapping = aes(x = Var2, y = Freq, fill = Var1)) +
geom_col(position = position_dodge()) +
labs(fill = "Anesthetic type", x = "Nausea") +
scale_x_discrete(labels = c("Yes", "No"))
Upvotes: 2