Daniel Valencia C.
Daniel Valencia C.

Reputation: 2279

Is there any way to use 2 color scales on the same ggplot?

With the data separated by categories (Samples A and B), 2 layers were made, one for points and one for lines. I want to separate my data by category indicating colors for the points and also separate the lines but with different colors than those used for the points.

library(ggplot2)

Sample <- c("a", "b")
Time <- c(0,1,2)

df <- expand.grid(Time=Time, Sample = Sample)
df$Value <- c(1,2,3,2,4,6)

ggplot(data = df,
             aes(x = Time,
                 y = Value)) +
  geom_point(aes(color = Sample)) +
  geom_line(aes(color = Sample)) +
  scale_color_manual(values = c("red", "blue")) + #for poits
  scale_color_manual(values = c("orange", "purple")) #for lines

Upvotes: 3

Views: 1296

Answers (2)

zx8754
zx8754

Reputation: 56179

Using colour columns and scale_color_identity:

df$myCol1 <- rep(c("red", "blue"), each = 3)
df$myCol2 <- rep(c("orange", "purple"), each = 3)

ggplot(data = df,
       aes(x = Time,
           y = Value)) +
  geom_point(aes(color = myCol1)) +
  geom_line(aes(color = myCol2)) +
  scale_color_identity()

enter image description here

Upvotes: 3

stefan
stefan

Reputation: 124213

Making use of the ggnewscale package this could be achieved like so:

library(ggplot2)
library(ggnewscale)
Sample <- c("a", "b")
Time <- c(0,1,2)

df <- expand.grid(Time=Time, Sample = Sample)
df$Value <- c(1,2,3,2,4,6)

ggplot(data = df,
       aes(x = Time,
           y = Value)) +
  geom_point(aes(color = Sample)) +
  scale_color_manual(name = "points", values = c("red", "blue")) + #for poits
  new_scale_color() +
  geom_line(aes(color = Sample)) +
  scale_color_manual(name = "lines", values = c("orange", "purple")) #for lines

Upvotes: 6

Related Questions