Color Coding Multiple conditions in ggplot

Viewed 479

I am trying to make a plot that captures data and color codes them based on multiple conditions.

I have successfully made a graph before using this code:

ggplot(data2_CY, aes(x = Date, y = AVERAGETOTALCOST)) + geom_point(color = 'blue') + geom_point(data = data2_CN, color = 'red') + 
  geom_point(data = data2_LY, color = 'cyan') + geom_point(data = data2_LN, color = 'magenta') + 
  labs(title = "Average Total Cost Trends Over Time", x = "Time", y = "Average Total Cost") + scale_x_date(breaks = seq(as.Date("2017-01-01"), as.Date("2019-07-01"), by = "6 months"), date_labels = "%b\n%Y")

The issue is that I used 4 separate dataframes, so I cannot create a legend using scale_color_manual() since it uses data from only one dataframe.

To work around this, I have combined the dataframes into one dataframe that looks like this:

Date       |  CL  | TF | AVERAGETOTALCOST  
2017-01-01 |   C  |  T | 12325.120
2017-01-01 |   C  |  F | 12504.443
2017-01-01 |   L  |  T | 2050.544
2017-01-01 |   L  |  F | 3055.342
2017-02-01 |   C  |  T | 14055.543

and so on...

How can I use ggplot to color code each of the 4 conditions? There are C&T, C&F, L&T, L&F. I have something along the lines of:

ggplot(data2_CL) + geom_point(aes(x = Date, y = AVERAGETOTALCOST) color = ) + scale_color_manual(value = )

but not sure how to proceed.

Thanks!

2 Answers

This could be achieved by concatenating your CL and TF columns aand mapping the new variable on the color aes like so:

data2_CL$color <- paste0(data2_CL$CL, data2_CL$TF)

library(ggplot2)

ggplot(data2_CL) + 
  geom_point(aes(x = Date, y = AVERAGETOTALCOST, color = color)) + 
  scale_color_manual(values = c(CT = "red", CF = "blue", LT = "green", LF = "purple"))

Use interaction to get all combinations of CL and TF present in the data.

library(ggplot2)

ggplot(data2_CL) + 
  geom_point(aes(x = Date, y = AVERAGETOTALCOST, color = interaction(CL, TF))) + 
  scale_color_manual(values = c("magenta", "red", "cyan", "blue")) +
  guides(color = guide_legend(title = "CL, TF"))

enter image description here


Data

data2_CL <-
structure(list(Date = structure(c(17167, 17167, 17167, 17167, 
17198), class = "Date"), CL = c("C", "C", "L", "L", "C"), 
TF = c("T", "F", "T", "F", "T"), AVERAGETOTALCOST = c(12325.12, 
12504.443, 2050.544, 3055.342, 14055.543)), 
row.names = c(NA, -5L), class = "data.frame")
Related