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

