Reputation: 443
When using setting the order of factor levels manually, I can't get both geom_point and geom_line to plot the data in the same order.
df <- data.frame(A=c(rep(c(5, 10, 15, 20, 25), 2)),
B=c(81, 86, 89, 94, 99, 81, 86, 89, 94, 100),
C=c(rep(0, 5), rep(1, 5)))
df$C <- factor(df$C, levels=c(1,0))
colors=c("red", "black")
ggplot(df, aes(A, B)) +
geom_point(aes(color=C)) +
geom_line(aes(color=C)) +
scale_color_manual(values=colors)
I want the 0's from C to be plotted last, which geom_line is doing, but geom_point is not. I don't understand why. How can I get them both to cooperate? If I don't set the factor levels of df$C and rather use dplyr::arrange(desc(C)), it still doesn't solve the discrepancy.
I'm using my own color palette, but even using the default colors, I get this issue.
Thanks!
Upvotes: 1
Views: 1491
Reputation: 2050
You can change the colors coming in
library(tidyverse)
colors=c("black", "red")
data.frame(A = c(rep(c(5, 10, 15, 20, 25), 2)),
B = c(81, 86, 89, 94, 99, 81, 86, 89, 94, 100),
C = c(rep(0, 5), rep(1, 5))) %>%
mutate(C = factor(C)) %>%
arrange(C) %>%
ggplot(aes(A, B, color=C)) +
geom_point() +
geom_line() +
scale_color_manual(values=colors) +
guides(color = guide_legend(reverse=TRUE))
Upvotes: -1
Reputation: 66490
Add this line to your data frame prep to sort the data frame by C
so that the 0's appear last and get drawn last (i.e. on top) by geom_point
.
df <- df[order(df$C),]
Upvotes: 3