0

Hey guys so this is what my data looks like:

data <- read.table(text ="
                    Call_Type, Violation_Type, Monthly_Average_Violations
                   Traditional, Total, 4.472
                   Traditional, Shift Length, 0.222
                   Traditional, Days Off, 2.667
                   Traditional, 80 Hour Week, 1.556
                   Nightfloat, Total, 5.417
                   Nightfloat, Shift Length, 0.000
                   Nightfloat, Days Off, 4.194
                   Nightfloat, 80 Hour Week, 1.167", 
                   header = TRUE, 
                   sep = ",")

And then I am using this to plot:

ggplot(data, aes(x = Violation_Type, 
                 y = Monthly_Average_Violations, 
                 fill = Call_Type)) +
  geom_bar(stat = "identity", position = "dodge") +
  theme(axis.text.x = element_text(angle = 90))

enter image description here

I apparently cannot embed pictures yet. I want to put the traditional bins first and I want them green, and the nightfloat bins second and I want them pink. Any help would be greatly appreciated.

Phil
  • 7,287
  • 3
  • 36
  • 66
Josh_PL
  • 25
  • 5
  • 1
    Does this answer your question? [Order Bars in ggplot2 bar graph](https://stackoverflow.com/questions/5208679/order-bars-in-ggplot2-bar-graph) – divibisan May 01 '20 at 14:43

1 Answers1

0

The easiest way to get discrete variables in a desired order is to change them to a factor and change the levels to order you want.

# For R>4.0.0 you can omit `as.character()`
data$Call_Type <- factor(as.character(data$Call_Type), c("Traditional", "Nightfloat"))

ggplot(data, aes(x=Violation_Type, y=Monthly_Average_Violations, fill=Call_Type))+
  geom_bar(stat="identity", position="dodge") +
  scale_fill_manual(values = c("green", "pink")) +
  theme(axis.text.x = element_text(angle = 90))

enter image description here

teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • So when I do this and plug it into R studio, I end up with a graph with just nightfloat bars for 80 hour week and shift length and traditional for total and days off. I like what yours looks like and wondering what I did wrong. – Josh_PL May 01 '20 at 15:14
  • What does your `data$Call_Type` data look like? – teunbrand May 02 '20 at 05:59