eliocamp / ggnewscale

Multiple Fill, Color and Other Scales in `ggplot2`
https://eliocamp.github.io/ggnewscale/
GNU General Public License v3.0
406 stars 18 forks source link

Show specific legend with ggnewscale #26

Closed lizhiwei1994 closed 4 years ago

lizhiwei1994 commented 4 years ago

ggnewscale is really a helpful package, but I have a little question about the package is it possible to show specific legend?

Such as only show the temp legend on the plot and drop the type legend. I know we can drop it using guide = 'none' in new_scale_fill() and new_scale_color(), but in my code I use new_scale('fill').

Any help will be highly appreciated!

library(scatterpie)
library(tidyverse)
library(geosphere)
library(ggnewscale)
us <- map_data('state') %>% as_tibble()

n = length(unique(us$region))

# creat fake mapping data

temperature_data <- tibble(region = unique(us$region),
                           temp = rnorm(n = n))

coords <- us %>% select(long, lat, region) %>% distinct(region, .keep_all = T)

category_data <- tibble(region = unique(us$region),
                        cat_1 = sample(1:100, size = n),
                        cat_2 = sample(1:100, size = n),
                        cat_3 = sample(1:100, size = n)) %>% left_join(coords)

us <- left_join(us, temperature_data)

p + geom_map(map = us, aes(map_id = region, fill = temp), color = 'grey') +
  new_scale('fill') +
  geom_scatterpie(data = category_data,
                  aes(long, lat),
                  cols = c("cat_1", "cat_2", "cat_3"), 
                  alpha = 0.5)
eliocamp commented 4 years ago

You need to use guide = "none" inside the scale_* call. Something like this:

p + geom_map(map = us, aes(map_id = region, fill = temp), color = 'grey') +
  scale_fill_continuous(guide = "none") +  # removes the guide associated with the map fill. 
  new_scale('fill') +
  geom_scatterpie(data = category_data,
                  aes(long, lat),
                  cols = c("cat_1", "cat_2", "cat_3"), 
                  alpha = 0.5)