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.

Jessica
  • 11
  • 1
  • 12
    `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"))`. – Gregor Thomas Feb 18 '19 at 22:59
  • 2
    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](https://stackoverflow.com/a/5490938/903061). I think you maybe saw the `levels<-` approach [here](https://stackoverflow.com/a/5210833/903061), I've commented and edited it to hopefully not be confusing in the future. – Gregor Thomas Feb 18 '19 at 23:06

0 Answers0