'Can't get graph colours/legend to work with double y-axis?
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")
)
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.
Solution 1:[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")
)
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)
Solution 2:[2]
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"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |
| Solution 2 | Quinten |


