Как использовать несколько символов, цвет и заполнить ggmap без изменения цвета легенды в R? - PullRequest
1 голос
/ 09 марта 2020

Я использую ggmap для построения некоторых заполненных точек через океан, но они перекрываются, поэтому я использовал colour=black, чтобы дать им схему. Когда я использую pch=21, легенда не меняется, а точки обведены черным, как я хочу. Но я также пытаюсь получить 3 разных символа на карте. Когда я указываю разные символы, все точки в легенде становятся черными.

Вот некоторые примеры данных и код, который я использовал для получения карты с правильной легендой, но с неправильными символами

#library
library(ggmap)
library(mapdata)
library(ggplot2)

#sample

mapoc_temp = data.frame(longitude= c(-64.5, -63.1, -62.4, -62.2, -66.0, -61.9), 
                                    latitude= c(42.7, 44.8, 45.8, 45.6, 43.0, 40.2),
                                    Zone = sample(c(1,4,6,7), 6, replace = T),
                                    location = sample(c(1,2,3), 6, replace = T))

#map
canada = map_data("worldHires")
ggplot(data = canada) +
  borders("world", xlim = c(-130, -60), ylim = c(20, 50), colour = "black", fill = "grey50") +
  geom_polygon(data = canada, aes(x=long, y = lat, group = group), fill = "grey50") +
  #coordinates of my map
  coord_sf(xlim=c(-84, -41), ylim=c(24,51), expand = FALSE) +
  #map the receiver locations
  geom_point(data = mapoc_temp,
             mapping = aes(x = longitude, 
                           y = latitude,
                           fill = Zone), 
             pch = 21,
             size = 15, colour = "black") +
  #fill the zones 
  scale_color_manual(values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) +
  scale_fill_manual(values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) 

и вот как выглядит карта enter image description here

Когда я пытаюсь добавить символы, я получаю правильные символы, но моя легенда больше не верна. Ниже приведен код и изображение.

ggplot(data = canada) +
  borders("world", xlim = c(-130, -60), ylim = c(20, 50), colour = "black", fill = "grey50") +
  geom_polygon(data = canada, aes(x=long, y = lat, group = group), fill = "grey50") +
  #coordinates of my map
  coord_sf(xlim=c(-84, -41), ylim=c(24,51), expand = FALSE) +
  #map the receiver locations
  geom_point(data = mapoc_temp,
             mapping = aes(x = longitude, 
                           y = latitude,
                           fill = as.factor(Zone)), 
             pch = pch = if_else(mapoc_temp$location == 1,25,
                                 if_else(mapoc_temp$location == 3, 23, 21)),
             size = 15, colour = "black") +
  scale_x_continuous(label = abs) +
  scale_y_continuous(label = abs) +
  #fill the zones in with viridis
  scale_color_manual(values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) +
  scale_fill_manual(values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361")) 

enter image description here

Кто-нибудь знает, как исправить легенду на втором изображении, чтобы точки были правильными цвета? Мне не нужны символы, чтобы быть в легенде

Ответы [ 2 ]

1 голос
/ 09 марта 2020

У меня нет ваших данных, поэтому я буду использовать хороший набор данных ol 'mtcars. Хитрость заключается в том, чтобы назначать фигуры вручную, в противном случае ggplot будет выдавать сообщение «Непрерывная переменная не может быть отображена на фигуру».

mtcars$shape <- ifelse(mtcars$cyl==4, 21, ifelse(mtcars$cyl==6, 23, 25))

ggplot(mtcars, aes(wt, mpg)) + 
   geom_point(aes(fill = factor(cyl), shape=factor(cyl)), col="black", size=3) +
   scale_shape_manual(values=c(21,23,25))

enter image description here


Для ваших собственных данных попробуйте:

mapoc_temp$shape <- factor(mapoc_temp$location + 20)

geom_point(data = mapoc_temp,
           mapping = aes(x = longitude, 
                         y = latitude,
                         fill = factor(Zone),
                         shape= shape),
           size = 15, colour = "black") +
  scale_shape_manual(values=c(21,22,23)) + # Must be same length as unique location.
  guides(shape=FALSE) + # If you don't want an extra shape legend.
  guides(fill = guide_legend(override.aes=list(shape=21))) # A necessary fudge
1 голос
/ 09 марта 2020

На самом деле, ваша проблема связана с ошибкой, описанной здесь: https://github.com/tidyverse/ggplot2/issues/2322.

До go больше, вы можете сделать:

ggplot(data = canada) +
  borders("world", xlim = c(-130, -60), ylim = c(20, 50), colour = "black", fill = "grey50") +
  geom_polygon(data = canada, aes(x=long, y = lat, group = group), fill = "grey50") +
  #coordinates of my map
  coord_sf(xlim=c(-84, -41), ylim=c(24,51), expand = FALSE) +
  #map the receiver locations
  geom_point(inherit.aes = FALSE, data = mapoc_temp,
             mapping = aes(x = longitude, 
                           y = latitude,
                           fill = factor(Zone),
                           shape = factor(location)),
             size = 5) +
  scale_x_continuous(label = abs) +
  scale_y_continuous(label = abs) +
  #fill the zones in with viridis
  scale_fill_manual(name = "Zone", values=c("#01579B", "#4FC3F7", "#ffa600", "#ff6361"), breaks = c("1","4","6","7")) +
  scale_shape_manual(values = c("1" = 21, "2" = 22, "3" = 24))+
  guides(fill = guide_legend(override.aes=list(shape=21)), shape = FALSE)

enter image description here

Как уже упоминалось @Edward, вы можете избавиться от легенды shape, добавив guides(shape = FALSE).

Отвечает ли она на ваш вопрос?

...