Reputation: 23
I'm trying to make a bar graph for publication, and I'm trying to show the change in operation types performed at our hospital before a curriculum implementation and after, "BR" and "AR" respectively. The types of operation are "Open", "Laparoscopic", and "Robotic". I would like the "BR" values to come before the "AR" values on my bar graph, but I can't seem to figure out how to get R to read them in that order (I'm fairly new to R and coding :( ). my data frame is named df
bin type cases_per_month
1 Open BR 18.35
2 Open AR 15.50
3 Laparoscopic BR 4.25
4 Laparoscopic AR 1.95
5 Robotic BR 0.10
6 Robotic AR 1.15
ggplot(data=df, aes(x=bin, y=cases_per_month)) + geom_bar(stat="identity")
data <- tapply(df$cases_per_month, list(df$type, df$bin), sum)
barplot(data, beside=T, col=c("black", "grey"),
main="Average Cases per Month,BR and AR: Ventral",
xlab="Case Type", ylab="Average Cases per Month")
legend(locator(1), rownames(data), fill=c("black","grey"))
because R reads "BR" and "AR" as atomic vectors, most of the commands I've tried won't let me reorder it how I want to
This is what I'm getting now. I also want my y axis to go up to 20, but I just need to google that, I'm sure
Upvotes: 1
Views: 175
Reputation: 28
This one's kinda tricky. Here's my solution:
# Load ggplot
library(ggplot2)
# Create data frame
bin <- c('Open', 'Open', 'Laparoscopic', 'Laparoscopic', 'Robotic', 'Robotic')
type <- c('BR', 'AR', 'BR', 'AR', 'BR', 'AR')
cases.per.month <- c(18.35, 15.5, 4.25, 1.95, .1, 1.15)
df <- data.frame(bin, type, cases.per.month)
# Reorder levels
df$type <- factor(df$type, c('BR', 'AR'))
# Plot BR and AR types side-by-side
ggplot(df, aes(x = bin, y = cases.per.month, fill = type)) + geom_bar(stat = 'identity', position = 'dodge')
Also, welcome to R!
Upvotes: 0
Reputation: 3710
Come on. You just need this.
data <- data[2:1, ]
Your figure is created by the barplot
function in the graphics
package instead of the ggplot2
package. The ggplot
line is useless in your scripts.
For your y axis
issue, use the ylim
parameter.
barplot(data,beside=T,col=c("black","grey"),
main="Average Cases per Month,BR and AR: Ventral",
xlab="Case Type",ylab="Average Cases per Month", ylim=c(0,20))
Upvotes: 3