Reputation: 1258
I apologize for the semmingly simple nature of this query, but I have been beating my head on why this does not work.
So, here is a simple reproducible example:
library(ggplot2)
dm <- diamonds
ggplot(dm, aes(x = cut, y = price)) + geom_violin()
and I get the following plot (as I should):
But I want the violins in the figure to be of the form
> "Ideal" "Fair" "Very Good" "Premium" "Good"
so I reorder the factor levels:
levels(dm$cut) <- levels(dm$cut)[c(5, 1, 3, 4, 2)]
levels(dm$cut)
[1] "Ideal" "Fair" "Very Good" "Premium" "Good"
However, when I try the following:
ggplot(dm, aes(x = cut, y = price)) + geom_violin()
I get the violins in the same order as before, but the labels in the order as I want them. How do I fix this problem? TIA for any help and suggestions!
Upvotes: 1
Views: 3759
Reputation: 12470
I always find it a bit frustrating to work with factors, to be honest. The mistake you made (and which I made several times before) is that this is simply not how you order levels of a factor, but for some reason, this is:
dm$cut <- factor(x = dm$cut, levels = c("Ideal",
"Fair",
"Very Good",
"Premium",
"Good"))
ggplot(dm, aes(x = cut, y = price)) + geom_violin()
Upvotes: 1