3
votes

I am trying to overlay two scatter plots in ggplot2. The goal is to make the outside part of dots colored according to one variable (6 categories, factor) and the inside filled with a gradient color of another continuous variable (numeric).

I wrote two pieces of code, each works on its own (please see screenshots below).

    ggplot(PCA_isotopes_2, aes(x=PC1, y=PC2)) +
              theme_classic() +
              geom_point(aes(color = factor(subspecies)), shape = 1, size = 2.95, stroke=1, alpha=5/6) +
              scale_color_manual(breaks = c("gutturalis", "rg.hybrids", "rt", "rustica", "tg", "tytleri"), values=c("#0066CC", "#9933CC", "#FFCC99", "#CC0000", "#33CC99", "#FFFF00")) 

ggplot(PCA_isotopes_2, aes(x=PC1, y=PC2)) +
          theme_classic() +  
          geom_point(aes(color = carbon.ratio), size = 2.88, alpha=5/6) +
          scale_colour_gradient(low = "blue", high = "yellow")

enter image description here

enter image description here

When I try to overlay them this way:

    p <- ggplot(PCA_isotopes_2, aes(x=PC1, y=PC2)) +
  theme_classic() +
  geom_point(aes(color = carbon.ratio), size = 2.88, alpha=5/6) +
  scale_colour_gradient(low = "blue", high = "yellow")

    p + geom_point(aes(color = factor(subspecies)), shape = 1, size = 2.95,         stroke=1, alpha=5/6) +
    scale_color_manual(breaks = c("gutturalis", "rg.hybrids", "rt", "rustica", "tg", "tytleri"), values=c("#0066CC", "#9933CC", "#FFCC99", "#CC0000", "#33CC99", "#FFFF00")) 

I get error messages:

"Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale. Error: Continuous value supplied to discrete scale".

I've spent a couple hours trying to figure out why it doesn't work. I will very appreciate help!

Thanks, Georgy

1

1 Answers

3
votes

In general you can only map an aesthetic once. Here is a workaround that uses a fill aesthetic for the continuous variable as an alternative, with shape = 21. However, I would prefer to map to a different aesthetic, such as shape, entirely, as in the second version.

library(tidyverse)
ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) +
  theme_classic() +
  geom_point(
    mapping = aes(colour = Species),
    shape = 1,
    size = 3,
    stroke = 2,
    alpha = 5 / 6
    ) +
  geom_point(
    mapping = aes(fill = Sepal.Length, colour = NA),
    size = 2.88,
    alpha = 5 /6,
    shape = 21
  ) +
  scale_fill_gradient(low = "blue", high = "yellow")

library(viridis)
#> Loading required package: viridisLite
ggplot(iris, aes(x = Petal.Length, y = Petal.Width)) +
  theme_classic() +
  geom_point(
    mapping = aes(colour = Sepal.Length, shape = Species),
    size = 3,
    alpha = 5 / 6
  ) +
  scale_colour_viridis()

Created on 2018-04-19 by the reprex package (v0.2.0).