0

I am attempting to combine two data sets and chart types into a single ggplot. I want to plot the main data in a line/connected dot plot (two observations of the same kind within each of 5 categories), and a set of n random observations in a 6th category as a dot plot, geom_point().

This issue I am having is that the order of the categories which I am trying to specify using factor levels is not maintained after adding the second geom_point() with the supplemental data. Example plots are below.

Anyone know how to force the order of the categories as specified by the factor levels?

main_data <- data.frame(variable = c(rep("min", 5), rep("max", 5)), category = c("apples", "bananas", "peaches", "pears", "melons"), value = c(seq(0.2, 0.28, by = 0.02), seq(0.8, 0.56, by = -0.06))) supplemental_data <- data.frame(variable = rep("random_observation", 10), category = rep("chicken", 10), value = runif(10, 0, 1)) all_data <- rbind(main_data, supplemental_data) %>% mutate(category = factor(category, levels = c("bananas", "peaches", "apples", "melons", "pears", "chicken"))) ggplot() + geom_line(data = all_data %>% filter(variable != "random_observation"), aes(x = category, y = value, group = variable, colour=variable), size = 1) + geom_point(data = all_data %>% filter(variable != "random_observation"), aes(x = category, y = value, group = variable, colour=variable)) + geom_point(data = all_data %>% filter(variable == "random_observation"), aes(x = category, y = value, group = variable), colour = "dark red") + scale_y_continuous(labels = scales::percent) + scale_colour_manual(values = c("Red", "Blue")) + theme(panel.background = element_rect(fill = "#C0C0C0", colour = "000000"), legend.position = "bottom") 

enter image description here

enter image description here

6
  • 1
    Restart your R session new and use the code you provided. I can' t reproduce your issue! Commented Jan 7, 2024 at 7:25
  • 1
    Agree with TarJae. Can't reproduce your issue using ggplot2 ‘3.4.4’. Commented Jan 7, 2024 at 9:05
  • Re-Loaded R and I get the same result. Anyone else? the order of x axis categories come out the same as the order the factor levels are specified? Commented Jan 7, 2024 at 9:35
  • 1
    Could you check your ggplot2 Version, i.e. packageVersion("ggplot2")? Perhaps that's the reason why we can't reproduce. As a reference: I get i.sstatic.net/HwLY1.png when running your code using ggplot2 3.4.4. Commented Jan 7, 2024 at 9:44
  • 1
    ... a workaround might be to force the order by setting the limits of the scale, i.e. + scale_x_discrete(limits = c("bananas", "peaches", "apples", "melons", "pears", "chicken")). Commented Jan 7, 2024 at 10:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.