I am trying to use facet_wrap to break up my data frame into individual plots based on one column. However, when I use levels, the title above each individual plot changes, but the data displayed in the chart does not.
Here's an example:
library(reshape2)
library(ggplot2)
levels(tips$sex) <- c("Male", "Female")
ggplot(tips, aes(x=total_bill, y=tip/total_bill))+
facet_wrap(~sex)+
geom_point(shape=1)
ggsave("prac.pdf")
This gives me a plot with Male on the left and Female on the right. The highest y data point is in the female graph.If I change the levels and have Female first, the Female label will appear on the left, but the highest y data point is now under male and still on the right.
levels(tips$sex) <- c("Male", "Female")
ggplot(tips, aes(x=total_bill, y=tip/total_bill))+
facet_wrap(~sex)+
geom_point(shape=1)
ggsave("prac.pdf")
Any suggestions? I'm working with a different data frame of values, but the above example shows the same problem that I am having.
levels(tips$sex) <- c("Male", "Female")
is a bad way to change levels - it says "whatever the first level is, call it "Male", and whatever the second level is, call it "Female". Instead, use thefactor
commend which will compare the values of thelevels
argument to what is already there.tips$sex <- factor(tips$sex, levels = c("Male", "Female"))
. – Jackelynjackeroofactor
method is what's usually recommended for a custom order, orreorder()
, if the order depends on numeric values in another column. E.g., this answer on facet order. I think you maybe saw thelevels<-
approach here, I've commented and edited it to hopefully not be confusing in the future. – Jackelynjackeroo