I'm trying to figure out how to transform my bar graph. Right now, the Gears
fill is in numerical order. I'm trying to be able to manually set the order of the Gears
fill in an arbitrary order.
All other examples that I have found tell me how to order them in descending or ascending order based upon the counts or values of the data. I'm trying to set the order manually in arbitrary order. So instead of 3-4-5, I'd like to manually tell it that I want the data presented as 3-5-4, or 5-3-4.
Here is what I have now:
library(data.table)
library(scales)
library(ggplot2)
mtcars <- data.table(mtcars)
mtcars$Cylinders <- as.factor(mtcars$cyl)
mtcars$Gears <- as.factor(mtcars$gear)
setkey(mtcars, Cylinders, Gears)
mtcars <- mtcars[CJ(unique(Cylinders), unique(Gears)), .N, allow.cartesian = TRUE]
ggplot(mtcars, aes(x=Cylinders, y = N, fill = Gears)) +
geom_bar(position="dodge", stat="identity") +
ylab("Count") + theme(legend.position="top") +
scale_x_discrete(drop = FALSE)
If there is any data manipulation to be done that doesn't involve ggplot2
, I'd like to do it using data.table
. Thanks for the help!