I am trying to figure out how to convert my histogram. Right now the padding Gearsis in numerical order. I am trying to manually set the filling order Gearsin random order.
All the other examples that I found tell me how to sort them in descending or ascending order based on calculations or data values. I am trying to set the order manually in random order. Therefore, instead of 3-4-5, I would like to manually say that I want the data to represent 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 kind of data manipulation that is not being performed that is not related to ggplot2, I would like to do it with data.table. Thanks for the help!