Manually set the order in which bars are filled in random order with ggplot2

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)

Cylinder graph

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!

+4
1

.

,

> x=factor(c("a","c","b"))
> x
[1] a c b
Levels: a b c

a c b, a b c, - .

, , , , , :

> z=factor(x,unique(x))
> z
[1] a c b
Levels: a c b

, - , c a b.

> y=factor(c("a","c","b"),levels=c("c","a","b"))
> y
[1] a c b
Levels: c a b

, :

> reorder(y,x,function(x)c(a=2,b=3,c=1)[x])
[1] a c b
attr(,"scores")
c a b 
1 2 3 
Levels: c a b

, , ,

ggplot2

+7

Source: https://habr.com/ru/post/1542557/


All Articles