Reputation: 27
So, I am doing several descending ordered barplots in R using ggplot. Each of these plots contains one bar named "others", which should always the last bar. How to realize this optimally? More generally: Is there an easy possibility to pick one bar of a bar plot and move it to the last position without manually changing all levels.
Many thanks in advance, chris
Upvotes: 0
Views: 1494
Reputation: 44708
The trick is to use factor, as follows
library(ggplot2) # for plots
# dummy data
dat <- data.frame(
letters = c("A","B","Other","X","Y","Z"),
probs = sample(runif(6)*10,6)
)
# not what we want
ggplot(dat, aes(letters, probs)) + geom_bar(stat = "identity")
# magic happens here
# factor, and push Other to end of levels using c(others, other)
dat$letters <- factor(
dat$letters,
levels = c(
levels(dat$letters)[!levels(dat$letters) == "Other"],
"Other")
)
ggplot(dat, aes(letters, probs)) + geom_bar(stat = "identity")
If you're using + coord_flip()
, use levels = rev(c(...))
for intuitive ordering
dat$letters <- factor(
dat$letters,
levels = rev(c(
levels(dat$letters)[!levels(dat$letters) == "Other"],
"Other"))
)
ggplot(dat, aes(letters, probs)) + geom_bar(stat = "identity") + coord_flip()
Upvotes: 1