Lukas Vlahos
Lukas Vlahos

Reputation: 49

Legend with un-plotted variable in ggplot2

I have data where each point lays on a spectrum between two centroids. I have generated a color for each point by specifying a color for each centroid, then setting the color of each point as a function of its position between its two centroids. I used this to manually specify colors for each point and plotted the data in the following way:

lb.plot.dat <- data.frame('UMAP1' = lb.umap$layout[,1], 'UMAP2' = lb.umap$layout[,2],
                          'sample' = as.factor(substr(colnames(lb.vip), 1, 5)), 
                          'fuzzy.class' = color.vect))
p3 <- ggplot(lb.plot.dat, aes(x = UMAP1, y = UMAP2)) + geom_point(aes(color = color.vect)) +
  ggtitle('Fuzzy Classification') + scale_color_identity() 
p3 + facet_grid(cols = vars(sample)) + theme(legend.) + 
  ggsave(filename = 'ref-samps_bcell-vip-model_fuzzy-class.png', height = 8, width = 16)

enter image description here

(color.vect is the aforementioned vector of colors for each point in the plot)

I would like to generate a legend of this plot that gives the color used for each centroid. I have a named vector class.cols that contains the colors used for each centroid and is named according to the corresponding class.

Is there a way to transform this vector into a legend for the plot even though it is not explicitly used in the plotting call?

Upvotes: 0

Views: 338

Answers (1)

Claus Wilke
Claus Wilke

Reputation: 17790

You can turn on legend drawing in scale_color_identity() by setting guide = "legend". You'll have to specify the breaks and labels in the scale function so that the legend correctly states what each color represents, and not just the name of the color.

library(ggplot2)

df <- data.frame(x = 1:3, y = 1:3, color = c("red", "green", "blue"))

# no legend by default
ggplot(df, aes(x, y, color = color)) +
  geom_point() +
  scale_color_identity()


# legend turned on
ggplot(df, aes(x, y, color = color)) +
  geom_point() +
  scale_color_identity(guide = "legend")

Created on 2019-12-15 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions