jwarz
jwarz

Reputation: 531

ggplot2 - Add two legends (geom_point and color_gradient)

I would like to have two different legends in my ggplot graphic. One for the color gradient and another one to explain the red marked dots.

The legend for the red circles should contain only one line and an individual text.

I am only able to create the color gradient scale, but not the other one:

data <- data.frame(A = runif(10, 0, 10), 
                   B = runif(10, 0, 10), 
                   color = runif(10, 0, 10), 
                   density = runif(10, 0, 10), 
                   red = rep(1:5, each=2))

ggplot(data, aes(A, B, color = color, alpha = 1/density)) +
  geom_point(shape = 16, size = 5, show.legend = T) +
  theme_minimal() +
  theme(axis.text=element_text(size=12, family = 'serif'),
        axis.title=element_text(size=16,face="bold", family = 'serif'),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.line = element_line(colour = "black")) +
  scale_color_gradient(low = "white", high = "black", name = "Scale", breaks = c(8,2), labels = c("max","min"))+
  geom_point(data = data[data$red == 1,],color="red",size=5, alpha = 0.7, show.legend = T) +
  scale_alpha(range = c(.5, .7), breaks = data$A[1], labels = c("1")) +
  scale_x_continuous(trans='log10', name = "A") +
  scale_y_continuous(trans='log10', name = "B") 

enter image description here

Upvotes: 2

Views: 599

Answers (1)

SCDCE
SCDCE

Reputation: 1643

Have to assign the aes() for the scale_alpha().

library(ggplot2)
data <- data.frame(A = runif(10, 0, 10), 
                   B = runif(10, 0, 10), 
                   color = runif(10, 0, 10), 
                   density = runif(10, 0, 10), 
                   red = rep(1:5, each=2))

ggplot(data, aes(A, B, color = color, alpha = 1/density)) +
  geom_point(shape = 16, size = 5, show.legend = T) +
  geom_point(data = data[data$red == 1,],color="red",size=5, alpha = 0.7, show.legend = T) +
  theme_minimal() +
  theme(axis.text=element_text(size=12, family = 'serif'),
        axis.title=element_text(size=16,face="bold", family = 'serif'),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.line = element_line(colour = "black")) +
  scale_color_gradient(low = "white", high = "black", name = "Scale", breaks = c(8,2), labels = c("max","min"))+
  scale_alpha(range = c(.5, .7), aes(breaks = data$A[1], labels = c("1"))) +
  scale_x_continuous(trans='log10', name = "A") +
  scale_y_continuous(trans='log10', name = "B") 

enter image description here

Upvotes: 1

Related Questions