Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Legend not changing colors in ggplot2

I am trying to plot a scatter plot with 22 variables, so they all need to have different markers. I thought of repeating some shapes and colors from RColorBrew, and everything works fine, except for the legend that does not update with the colors I selected (please see image below). I also attached a working example below. What could I possibly be doing wrong?

#!/usr/bin/env Rscript

library(ggplot2)
library(ggpubr)
library(RColorBrewer)

theme_set(
    theme_pubr()
  )

data <- data.frame(
    x = c(1:22),
    y = as.factor(c(1:22))
)

shapes <- rep(15:18, 6)

colors <- rep(brewer.pal(n = 11, name = "Paired"), 2)

plot <- ggplot(data, aes(x=x, y=y, group=y, size=9, color=colors)) +
  geom_point(aes(shape=y)) +
  scale_shape_manual(values=shapes) +
  scale_size(guide="none") +
  guides(fill="none", color="none")

plot <- plot + theme(panel.grid.major=element_line(colour="gray", size=0.2),
  panel.grid.minor=element_line(colour="gray", size=0.2))

print(plot)

Black Legend

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are two issues:

  1. I you want to have your colors make use of scale_color_manual and map y on the color aes as you did with shape

  2. The reason your legend does not get colored is that you have set guides(color = "none")

library(ggplot2)
library(ggpubr)
library(RColorBrewer)

theme_set(
  theme_pubr()
)

data <- data.frame(
  x = c(1:22),
  y = as.factor(c(1:22))
)

shapes <- rep(15:18, 6)

colors <- rep(brewer.pal(n = 11, name = "Paired"), 2)

plot <- ggplot(data, aes(x = x, y = y, group = y, size = 9)) +
  geom_point(aes(shape = y, color = y)) +
  scale_shape_manual(values = shapes) +
  scale_color_manual(values = colors) +
  scale_size(guide = "none") +
  guides(fill = "none")

plot + theme(
  panel.grid.major = element_line(colour = "gray", size = 0.2),
  panel.grid.minor = element_line(colour = "gray", size = 0.2)
)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading