Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot guide_legend argument changes continuous legend to discrete

Tags:

r

ggplot2

Using the guide_legend argument, even without specifiying any further arguments, changes my legend from a continuous legend to a discrete one. I need to correct this (e.g. to use this: Add a box for the NA values to the ggplot legend for a continous map and then order the legends.)

df <- expand.grid(X1 = 1:10, X2 = 1:10)
df$value <- df$X1 * df$X2

ggplot(df, aes(X1, X2)) + 
  geom_tile(aes(fill = value))

The Legend on the right side is continuous

ggplot(df, aes(X1, X2)) + 
  geom_tile(aes(fill = value))+
  scale_fill_continuous(guide = guide_legend())

The legend now is discrete

The same happens, if I specify the argument when adding it as a + guides(fill = guide_legend())

Any ideas how to make sure the legend stays unchanged, so that I can use e.g. the order argument.

Thanks!

like image 341
Moritz Schwarz Avatar asked Jan 27 '26 21:01

Moritz Schwarz


1 Answers

Thanks to Ilkyun Im and chemdork123 for providing me with the answers.

The right command here would be guide_colorbar().

So it would be:

ggplot(df, aes(X1, X2)) + 
  geom_tile(aes(fill = value))+
  scale_fill_continuous(guide = guide_colorbar())

I still find it odd that the guide_legend() is not a general command, but specific to discrete legends. Oh well :)

like image 142
Moritz Schwarz Avatar answered Jan 30 '26 13:01

Moritz Schwarz