-1

I'm not sure why I'm getting my colors backward. Can someone please explain how the colors are assigned in this code? I'm trying to use examples on ggplot2 reference site, but I've been stuck on this for a long time. Here's the code:

#libraries
library(ggplot2)
library(scales)
library(reshape2)

#data
client.data <- read.csv('client.total.sorted.csv', header = TRUE, sep = ",")

#plot
ggplot(data = client.sorted) +
    geom_smooth(mapping = aes(x = Date, y = Cancelled, color = "red")) +
    geom_point(mapping = aes(x = Date, y = Cancelled, color = "red")) +
    geom_smooth(mapping = aes(x = Date, y = Active, color = "green")) +
    geom_point(mapping = aes(x = Date, y = Active, color = "green")) +
    labs(title = "activations vs cancellations", x = "Date", y = "")

Here's the output: enter image description here

ILikeWhiskey
  • 551
  • 5
  • 12
  • 8
    Move the color specification outside of `aes()`. But typically we don't specify colors this way in ggplot. Instead we would convert that data from wide to long, so that Active and Cancelled are values in a column in your data. *THEN* you can map color to that variable inside of `aes()`. It's the difference between mapping and setting aesthetics. – joran Mar 14 '18 at 21:58
  • @joran thanks for the help. Moving the color outside the aesthetic did what you said it would. The current data is set like this: > Date Active Cancelled - Are you saying that I should melt this so that Active and Cancelled are in the same column? I'm not sure how that would look. – ILikeWhiskey Mar 15 '18 at 14:05
  • Yes, exactly. You could use `tidyr::gather()` and end up with columns Date, Group and Value, where Group is either Active or Cancelled. Then you would have only _one_ `geom_smooth` and `geom_point` layer and you would _map_ color to Group. That's the correct way to use ggplot. Except for unusual cases, if you are adding multiple layers like this it's a sign that you haven't arranged your data correctly. – joran Mar 15 '18 at 15:04

1 Answers1

2

I found this post referencing legends that helped me solve this:

Add legend to ggplot2 line plot

The solution that worked for me is this:

ggplot(data = client.sorted) +
    geom_smooth(mapping = aes(x = Date, y = Cancelled, color = "CancelledLines")) +
    geom_point(mapping = aes(x = Date, y = Cancelled, color = "CancelledPoints")) +
    geom_smooth(mapping = aes(x = Date, y = Active, color = "greenLines")) +
    geom_point(mapping = aes(x = Date, y = Active, color = "greenPoints")) +
    scale_color_manual("",
                       breaks = c("CancelledLines", "CancelledPoints", "greenLines", "greenPoints"),
                       values = c("red", "red", "green", "green")) +
    labs(title = "activations vs cancellations", x = "Date", y = "")

enter image description here

ILikeWhiskey
  • 551
  • 5
  • 12