0

This code produces a black line for BrentSpot and a red line for CPI. When I add more lines/variables to the graph none of the colours match up.

ggplot(modified) +
  geom_line(aes(Month, BrentSpot)) +
  geom_line(aes(Month, CPI, colour = 'green')) +
  theme_minimal() +
  scale_y_continuous(
    "Brent Spot Price", 
    sec.axis = sec_axis(~ . * 1.1, name = "CPI")
  )
Quinten
  • 35,235
  • 5
  • 20
  • 53
Daedomdan
  • 73
  • 5
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. If you want to hard code color values, either place them outside the `aes()` or use `scale_color_identity()` – MrFlick Mar 10 '22 at 17:53

2 Answers2

1

It looks as though your data is in long format, with the price variable split across multiple columns (BrentSpot and CPI).

When this is the case and you want a legend, you need to give each line a colour mapping inside aes.

I have created a data set (see below) that should hopefully match yours in terms of names and column types to demonstrate:

library(ggplot2)

ggplot(modified) +
  geom_line(aes(Month, BrentSpot, colour = "Brent")) +
  geom_line(aes(Month, CPI, colour = 'CPI')) +
  theme_minimal() +
  scale_color_manual(values = c("red4", "green4")) +
  scale_y_continuous(
    "Brent Spot Price", 
    sec.axis = sec_axis(~ . * 1.1, name = "CPI")
  )

enter image description here


Data

set.seed(1)

modified <- data.frame(Month     = seq(as.Date("2020-01-01"), 
                                       as.Date("2021-12-01"),
                                       by = "month"),
                       BrentSpot = cumsum(rnorm(24)) + 100,
                       CPI       = cumsum(rnorm(24)) + 100)
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
1

I created a sample dataset:

modified <- data.frame(Month = c(1, 2, 3, 4, 5, 6),
                       BrentSpot = c(1, 3, 2, 4, 5, 2),
                       CPI = c(2, 4, 3, 1, 5, 6))

Output:

  Month BrentSpot CPI
1     1         1   2
2     2         3   4
3     3         2   3
4     4         4   1
5     5         5   5
6     6         2   6

You can add colors to the scale_color_manual. You can use this code:

ggplot(modified) +
  geom_line(aes(Month, BrentSpot, colour = "Brent")) +
  geom_line(aes(Month, CPI, colour = "CPI")) +
  theme_minimal() +
  scale_y_continuous(
    "Brent Spot Price", 
    sec.axis = sec_axis(~ . * 1.1, name = "CPI")
  ) +
  scale_color_manual(values=c("#CC6666", "#9999CC"))

Output: enter image description here

Quinten
  • 35,235
  • 5
  • 20
  • 53