0

I can't add the legend while using geom_polygon and geom_text (without geom_map) and leaving ggplot() arguments empty.

I have a shapefile and I want to plot that in ggplot2 package using geom_polygon. I have defined a fill variable to color some provinces with certain colors. Also, I want to add geom_text and some text to the plot. so, I have a dataset for geom_polygon and a dataset for geom_text so I can't define my dataset in ggplot() and I have to leave it without any defined arguments (the option legend = T is available only in ggplot()). Even when I add legend = T still the legend won't show in the resulting plot.

setwd("E:\\clustering")
library(readstata13)
library(maptools)
#> Warning: package 'maptools' was built under R version 3.5.3
#> Loading required package: sp
#> Checking rgeos availability: TRUE
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.5.3
data=read.dta13("data_cluster_gbd.dta",nonint.factors = T)
province=readShapePoly("province_map_created.shp")
#> Warning: readShapePoly is deprecated; use rgdal::readOGR or sf::st_read
names(province)
#> [1] "province" "name_En"  "std_ID"   "Adj_ID"
map=fortify(province,region = "std_ID")
names(map)
#> [1] "long"  "lat"   "order" "hole"  "piece" "id"    "group"
names(data)[1]="std_ID"
map=merge(map,data, by.x="id",by.y="std_ID", all = T)
map$cl_MB=addNA(map$cl_MB)
map$select[map$id%in%c(5,9,11,21,23,24)]="Selected"
map$select[!map$id%in%c(5,9,11,21,23,24,30)]="Not selected"
map$select[map$id==30]="No data"
map$select=factor(map$select,levels = c("Selected","Not selected","No data"))
levels(map$select)
#> [1] "Selected"     "Not selected" "No data"
cord.dec = SpatialPoints(cbind(map$long, map$lat), proj4string = CRS("+proj=longlat"))
map$long <- spTransform(cord.dec, CRS("+init=epsg:32739"))@coords[,1]
map$lat <- spTransform(cord.dec, CRS("+init=epsg:32739"))@coords[,2]
head(map)
#>   id     long      lat order  hole piece group location     pm10 alafkosh
#> 1  0 442192.7 13936534     1 FALSE     1   0.1  Markazi 76.27017    34846
#> 2  0 442242.9 13936502     2 FALSE     1   0.1  Markazi 76.27017    34846
#> 3  0 442469.5 13936501     3 FALSE     1   0.1  Markazi 76.27017    34846
#> 4  0 442519.4 13936470     4 FALSE     1   0.1  Markazi 76.27017    34846
#> 5  0 442796.4 13936468     5 FALSE     1   0.1  Markazi 76.27017    34846
#> 6  0 442871.7 13936436     6 FALSE     1   0.1  Markazi 76.27017    34846
#>   gharchkosh hasharekosh cancer_all_ages_ir cancer_asir asthma_all_ages_mr
#> 1      34012       42975           171.4821    149.5961           11.09847
#> 2      34012       42975           171.4821    149.5961           11.09847
#> 3      34012       42975           171.4821    149.5961           11.09847
#> 4      34012       42975           171.4821    149.5961           11.09847
#> 5      34012       42975           171.4821    149.5961           11.09847
#> 6      34012       42975           171.4821    149.5961           11.09847
#>   asthma_asmr copd_all_ages_mr copd_asmr crd_all_ages_mr crd_asmr
#> 1    8.701504         16.21552  12.45099        31.42408 24.43511
#> 2    8.701504         16.21552  12.45099        31.42408 24.43511
#> 3    8.701504         16.21552  12.45099        31.42408 24.43511
#> 4    8.701504         16.21552  12.45099        31.42408 24.43511
#> 5    8.701504         16.21552  12.45099        31.42408 24.43511
#> 6    8.701504         16.21552  12.45099        31.42408 24.43511
#>   asthma_all_ages_ir asthma_asir copd_all_ages_ir copd_asir
#> 1           622.8062    723.4797          114.362  108.6879
#> 2           622.8062    723.4797          114.362  108.6879
#> 3           622.8062    723.4797          114.362  108.6879
#> 4           622.8062    723.4797          114.362  108.6879
#> 5           622.8062    723.4797          114.362  108.6879
#> 6           622.8062    723.4797          114.362  108.6879
#>   crd_all_ages_ir crd_asir wealth_index wealth_index_q cl_MB       select
#> 1        740.0908 834.9011    0.5602894              5     1 Not selected
#> 2        740.0908 834.9011    0.5602894              5     1 Not selected
#> 3        740.0908 834.9011    0.5602894              5     1 Not selected
#> 4        740.0908 834.9011    0.5602894              5     1 Not selected
#> 5        740.0908 834.9011    0.5602894              5     1 Not selected
#> 6        740.0908 834.9011    0.5602894              5     1 Not selected
centroid = aggregate(cbind(long, lat) ~ location, data = map, FUN = function(x) mean(range(x)))
centroid=merge(x = centroid, y = map[,c("location","cl_MB","group")], by = "location", all.x = T)
centroid=centroid[!duplicated(centroid),]
centroid=na.omit(centroid)
head(centroid)
#>               location      long      lat cl_MB group
#> 1               Alborz 482830.93 13977691  <NA>  30.1
#> 1599           Ardabil 245430.51 14254436     6  24.1
#> 4517  Azerbaijan, East 123307.52 14221990     2   3.1
#> 8252  Azerbaijan, West  37824.88 14208963     6   4.1
#> 20096          Bushehr 552982.75 13184877     5  18.1
#> 26747          Bushehr 552982.75 13184877     5  18.2
sample=c("forestgreen","grey","black")
ggplot(legend = T) +
  geom_polygon(data = map, mapping = aes(x = long, y = lat, group = group, fill = select), colour = "black",size = 10^(-100000000)) +
  geom_text(data = centroid, mapping = aes(x = long, y = lat, label = cl_MB), size = 2) +
  coord_fixed() + 
  xlab("") + ylab("") + 
  scale_fill_manual(map,name = "Clusters", values = sample, drop = F) +
  theme_bw() +
  theme(
    legend.position = "right",
    legend.title = element_blank(),
    plot.margin = unit(c(0,0,0,0),"cm"),
    plot.title = element_text(hjust = 0.5),
    axis.ticks = element_blank(),
    axis.title=element_blank(),
    axis.text = element_blank(),
    strip.background = element_rect(fill = "white"),
    plot.background = element_blank(),
    panel.grid = element_blank(),
    panel.border = element_blank()
  )

After running this code, the legend for the fill variable (select) still won't show! I've also tried adding the argument Show.legend = T to geom_polygon and It didn't work. enter image description here

M. white
  • 80
  • 7
  • Welcome to Stack Overflow! Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Nov 10 '19 at 07:00
  • I've edited the codes and added the image of the result. @Tung – M. white Nov 10 '19 at 08:42
  • Looking at the code, my guess is the error is with this line "scale_fill_manual(map,name = "Clusters", values = sample, drop = F)". Replace the map with "map" or something else. I cannot say for sure, and like @Tung please dput you code so we can reproduce the problem you have to help you better – StupidWolf Nov 10 '19 at 14:19
  • Thanks for your comment! The problem was using map as an input in scale_fill_manual. when I omitted it, the legend showed up in the resulting plot. @StupidWolf – M. white Nov 11 '19 at 07:45
  • great @M.white, yeah scales don't take in a data input. next time try to share an example of data, help others help you, for example dput(map) in this example. – StupidWolf Nov 11 '19 at 08:00

0 Answers0