Reputation: 86
How do I reorder the bars if I am using just one variable?
cbp2 <- c("#44bcd8", "#b97455", "#042f66", "#1c100b",
"#ff3300", "#006600", "#660033", "#660066","#ffcc00","#99ff99","#669999")
ggplot(data = diamonds)+
geom_bar(mapping = aes(color, fill=cut))+
theme(aspect.ratio = 1) +
scale_fill_manual(values = cbp2)+
labs(x = NULL, y = NULL)+
coord_flip()
To reoder, I tried to use geom_bar(mapping = aes(x=reorder(color, fill=cut))
but it doesn't work. Tried to look on the web but all examples include both x and y in aes()
. Any suggestions?
Upvotes: 1
Views: 734
Reputation: 465
Not quite sure what order you wish to re-order x
to, but fct_reorder
(from forcats
library) accepts a range of helpful functions.
Key point: wrap only the mapped variable you wish to reorder in fct_reorder
- in your example above you have included fill in the reorder
call.
If you wish to reorder by the count of each colour:
library(ggplot2)
library(forcats)
ggplot(data = diamonds)+
geom_bar(mapping = aes(fct_reorder(color, cut, .fun = 'length'), fill=cut))+
theme(aspect.ratio = 1) +
scale_fill_manual(values = cbp2)+
labs(x = NULL, y = NULL)+
coord_flip()
More examples here: https://www.r-graph-gallery.com/267-reorder-a-variable-in-ggplot2.html
Upvotes: 2
Reputation: 3252
Used the library forcats
and the function fct_rec()
library(forcats)
library(ggplot2)
cbp2 <- c("#44bcd8", "#b97455", "#042f66", "#1c100b",
"#ff3300", "#006600", "#660033", "#660066","#ffcc00","#99ff99","#669999")
ggplot(data = diamonds)+
geom_bar(mapping = aes(fct_rev(color), fill=cut))+
theme(aspect.ratio = 1) +
scale_fill_manual(values = cbp2)+
labs(x = NULL, y = NULL) +
coord_flip()
Upvotes: 0