R ggplot2 facet_wrap isn't changing data according to Factor level
Asked Answered
H

0

1

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.

Halmstad answered 18/2, 2019 at 22:54 Comment(2)
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 the factor commend which will compare the values of the levels argument to what is already there. tips$sex <- factor(tips$sex, levels = c("Male", "Female")).Jackelynjackeroo
The factor method is what's usually recommended for a custom order, or reorder(), if the order depends on numeric values in another column. E.g., this answer on facet order. I think you maybe saw the levels<- approach here, I've commented and edited it to hopefully not be confusing in the future.Jackelynjackeroo

© 2022 - 2024 — McMap. All rights reserved.