-1

How can I add legend to this plot.

scatter plot showing density

My code is as follows :

d1 = densCols(data4$x, data4$y, 
              colramp = colorRampPalette(c("navy blue","yellow","firebrick","firebrick"), 
              space = "Lab"))

ggplot(data4) + 
  geom_point(aes(x=x, y= y, col = d1), size = 0.1) + 
  scale_color_identity() + 
  theme_bw() + 
  theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) + 
  labs(x="xaxis", y="yaxis", title="xyz cells") + 
  theme(plot.title = element_text(hjust = 0.5))

theme(legend.position=c(1,1),legend.justification=c(1,1))

I tried this and various other things mentioned but don't know why it is not working.

Thanks a lot for the help in advance.

Ok after adding scale_color_identity(guide = "legend"). My graph looks something like this

! scale_color_identity(guide = "legend")

Goku
  • 33
  • 5

1 Answers1

0

Unlike other scales, scale_*_identify()'s default value of guide is "none", which means no legend. So, you need to set guide = "legend" manually.

ggplot(data4) + 
  geom_point(aes(x=x, y= y, col = d1), size = 0.1) + 
  scale_color_identity(guide = "legend") + 
...

The examples in the documentation illustrates this well: http://ggplot2.tidyverse.org/reference/scale_identity.html

(By the way, I recommend you to try to make your example more simple and reproducible. See How to make a great R reproducible example? aka MCVE (Minimal, Complete, and Verifiable Example))

yutannihilation
  • 798
  • 4
  • 9
  • My legend looks weird. It does not have color gradient and number of bins as you would expect. How do I add my plot in the comment section. – Goku Nov 29 '17 at 15:55