简体   繁体   中英

Continuous legend to discrete scale in ggplot2

I am trying to plot continuous data (or converted to a factor with 104 levels, which represent values from 1 to 800) with a viridis color palette. If I leave the data continuous, some of the lower level facets cannot be distinguished by color. But the legend looks as it should (continuous). If I discretize the data and plot it, the colors are easier to distinguish, but I cannot use the legend, as it has 104 bins. In addition, if I use the discretized data with a continuous scale, I get the right result, but the legend shows a limit of 104, instead of the values (various values from 1 to 800). How can I plot the factor levels with easily distinguishable colors but a continous scale that shows that the values go up to 800?

I tried new_scale_color, but that does also not work.

 # first layer: all countries, no fill, no white outlines
  geom_polygon(data = maps2, 
               aes(x = long, y = lat, group = group), fill="grey", show.legend = F, size = 0.1) +

# ​this gives me the right legend, but the lower factor levels are not distingishable in the graph, they all have the same color. 

  geom_polygon(data = test,
            aes(x = long, y = lat, group = group, fill = 
 citation_tally), show.legend = F)+ 

 # This, combined with as.factor(citation_tally) gives me distinguishable colors but a huge legend. 

 # scale_fill_viridis_d("discrete",option="D", na.value = NA)+

 # this changes the colors and makes them again indistinguishable
 
scale_fill_binned(type= "viridis")+ 

  theme(plot.title = element_text(hjust = 0.5, size = 6),
        axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks = element_blank(),
        axis.title.y=element_blank(),
        axis.title.x=element_blank(),
        rect = element_blank())+
  coord_fixed(1.3)+
  theme(plot.margin=unit(c(0.5,0.5,0.5,0.5), "cm"))


[![Continuous scale, legend is nice - colors indistinguishable][1]][1]


[![Discrete scale, colors are nice, but the legend is huge][2]][2]


  [1]: https://i.stack.imgur.com/6vJLA.png
  [2]: https://i.stack.imgur.com/QuN7C.png

Your data is not categorical, so you shouldn't use a discrete scale, nor use factor() at all. One of the symptoms of this is the huge legend as you have mentioned.

Try plotting your continuous data, but then using plot + scale_fill_binned() which will give you a binned scale (which seems to be what you want), but not a discrete scale. For more information refer to the documentation on this function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM