2

I would like to create a grayscale line-graph with multiple groups (~10), but having one line (spec=3) that is in red.

See an example with only 3 groups below:

year <-c (2011, 2012, 2013, 2011, 2012, 2013, 2011, 2012, 2013)
x <- 1:10
cost <- sample(x, 9, replace=T)
spec <- as.factor(c(1, 1, 1, 2, 2, 2, 3, 3, 3))

dat <-data.frame(year=year, cost=cost, spec=spec)

# graph
library(ggplot2)
ggplot(data=dat, aes(x=year, y=cost, group=spec)) +
  geom_line(aes(color=spec)) + 
  **geom_line(group="3", col="red")** + 
  scale_colour_grey() + 
  theme_bw()

The problem is obviously with the geom_line(group="3", col="red") part, but I don't know how to fix it.

With this code I get something strange like this: enter image description here

Ekatef
  • 1,061
  • 1
  • 9
  • 12
Stata_user
  • 562
  • 3
  • 14

2 Answers2

1

You only need to define aes(color = ) once, then dial in you colors via a named custom color palette.

ggplot(data=dat, aes(x=year, y=cost, group=spec)) +
  geom_line(aes(color=spec)) + 
  # geom_line(group="3", col="red") +
  scale_color_manual(values = c("1" = "black", "2" = "grey", "3" = "red")) +
  # scale_colour_grey() +
  theme_bw()
Nate
  • 10,361
  • 3
  • 33
  • 40
  • 4
    If you want a lot of grayscale colors and one red color you could customize the color scale something like this: `scale_color_manual(values = c(gray.colors(9), 'red'))` – qdread Aug 22 '19 at 12:56
0

I think this might do the trick, perhaps a bit of an overkill with the melt call, but should be really straightforward and is the most flexible approach, which also incorporates a comment made on another answer. I used this https://stackoverflow.com/a/53264920/5795592 as the starting point. Should be flexible enough.

library(data.table)
library(dplyr)
melt(dat, measure.vars="cost", id.vars = c("year","spec") ) %>% ggplot(data=., aes(x=year, y=value)) +
    geom_line(aes(color=spec), data = . %>% subset(., spec %in% c("1","2"))) +
    geom_line(aes(color=spec), data = . %>% subset(., spec %in% c("3"))) +
    scale_color_manual(values = c(gray.colors(2), 'red')) 

Result

hannes101
  • 2,410
  • 1
  • 17
  • 40