0

I want to plot proper graph with lable, title and legend. here is my attempt to produce legend. but why this error comeout. is there extra package I missed to load? Details on my data available here . Kindly help.. Thank you

library(ggplot2)
ggplot() + 
geom_line(data = Press_1000, aes(as.Date(date), temp_c), color = "darkblue") +
geom_line(data = Press_925, aes(as.Date(date), temp_c), color = "red") +
scale_color_discrete(name = "Pressure Level", labels = c( "1000", "925"))
#graph plotted without legend 

ggplot() + 
geom_line(data = Press_1000, aes(as.Date(date), temp_c), color = "Y1") +
geom_line(data = Press_925, aes(as.Date(date), temp_c), color = "Y2") + 
scale_color_manual(values = c('Y1' = 'darkblue','Y2' = 'red')) +
labs(color = "Pressure Level")
#Error in grDevices::col2rgb(colour, TRUE) : invalid color name 'Y1'

ggplot() + 
geom_line(data = Press_1000, aes(as.Date(date), temp_c), color = "a") +
geom_line(data = Press_925, aes(as.Date(date), temp_c), color = "b") + 
scale_color_manual(name = "Colors", values = c("a" = "blue", "b" = "red"))
#Error in grDevices::col2rgb(colour, TRUE) : invalid color name 'a'
Siti Sal
  • 119
  • 2
  • 12
  • 2
    You need to put the color = ... inside aes. – Roland Oct 04 '18 at 11:21
  • You should provide enough information for a [minimal reproducible example](https://stackoverflow.com/a/5963610/2359523) so that others can reproduce your problem. But as Roland pointed out, place your color within `aes` rather than outside of it. – Anonymous coward Oct 04 '18 at 16:39

1 Answers1

0

As pointed by Roland, you have to use aes(...) to solve this.

Using your first example, the problem is that you need to define the color variable in the aes(...) part to get fixed levels:

ggplot() + 
    geom_line(data = Press_1000, aes(as.Date(date), temp_c, color = "a")) +
    geom_line(data = Press_925, aes(as.Date(date), temp_c, color = "b")) +
    scale_color_discrete(name = "Pressure Level", labels = c( "1000", "925"))

Then your color scale will have two level "a" and "b". Because you "force" them to be "a" and "b". You can afterwards change their color using the values = ... argument in the scale_color_discrete() function to change its color.

When the color are defined outside aes(...) they are fixed manually. Thus only R color values are tolerated by ggplot2. When they are defined using strings inside aes(...) they are considered as categories and can further be used in the scale_color_...() function.

Rekyt
  • 354
  • 1
  • 8