r - Manually set order of fill bars in arbitrary order using ggplot2 -


this question has answer here:

i'm trying figure out how transform bar graph. right now, gears fill in numerical order. i'm trying able manually set order of gears fill in arbitrary order.

all other examples have found tell me how order them in descending or ascending order based upon counts or values of data. i'm trying set order manually in arbitrary order. instead of 3-4-5, i'd manually tell want data presented 3-5-4, or 5-3-4.

here 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 data manipulation done doesn't involve ggplot2, i'd using data.table. help!

you need set factor levels correctly.

let's suppose have factor

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

the order a c b, plotting order a b c, since default factor generates levels in alphanumeric order.

perhaps want plotting order match order in vector-we can specify factor levels should follow order in each level first encountered:

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

perhaps want neither of these - example might want c b.

we can manually set order

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

or can adjust factor later on explicitly specifying position of each level:

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

now know this, can apply techniques found elsewhere, such

order bars in ggplot2 bar graph


Comments

Popular posts from this blog

php - render data via PDO::FETCH_FUNC vs loop -

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

The canvas has been tainted by cross-origin data in chrome only -