1
votes

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)

enter image description here

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!

2
What do you mean with "the 0's from C to be plotted last"?apitsch
The data from group 0, as denoted by column C. Wanted them to be plotted after the points from group 1.hmg

2 Answers

3
votes

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),]

enter image description here

-1
votes

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

enter image description here