user3236841
user3236841

Reputation: 1258

ggplot2: ordering factor levels appears to have no effect on figure

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):

enter image description here

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! enter image description here

Upvotes: 1

Views: 3759

Answers (1)

JBGruber
JBGruber

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()

enter image description here

Upvotes: 1

Related Questions