简体   繁体   中英

Error in “scale_fill_manual”

I manage to plot these to data sets separately, but when I try to combine them in one plot I get the error message: “Error: Insufficient values in manual scale. 34 needed but only 8 provided.” The problem is in the scale_fill_manual () Could someone please help me solve this problem. I hope the generated data works.. I still get the same error

Generate data

i_country<-wrld_simpl@data$NAME[1:26]

e_country<-wrld_simpl@data$NAME[27:34]

i <- data.frame(
     country = i_country,
     import = c(sample(10:10000, 26)))

e <- data.frame(
     country =e_country,
     export = c(sample(10:10000, 8)))

prepare wrld_simpl data

data(wrld_simpl)
wrld_simpl@data$id <- wrld_simpl@data$NAME
wrld <- fortify(wrld_simpl, region="id")
wrld <- subset(wrld, id != "Antarctica")

i$brk <- cut(i$import, 
         breaks=c(0, sort(i$import)), 
         labels=as.character(i[order(i$import),]$country),
         include.lowest=TRUE)

e$brk <- cut(e$export, 
         breaks=c(0, sort(e$export)), 
         labels=as.character(e[order(e$export),]$country),
         include.lowest=TRUE)

Plot

 library(ggplot2)

gg <- ggplot() + 
   geom_map(data=wrld, map=wrld, aes(map_id=id, x=long, y=lat), fill="white", color="#7f7f7f", size=0.25) +
   geom_map(data=i, map=wrld, aes(map_id=country, fill=brk),  color="white", size=0.25) + 
   geom_map(data=e, map=wrld, aes(map_id=country, fill=brk),  color="white", size=0.25) +
   scale_fill_manual(data=i, values=colorRampPalette(brewer.pal(9, 'Reds'))(length(i$import)), name="Export country") +
   scale_fill_manual(data=e, values=colorRampPalette(brewer.pal(9, "Greens"))(length(e$export)), name="Import country") +
   coord_map() + 
   theme(plot.background = element_rect(fill = "transparent", colour = NA),
         panel.border = element_blank(),
         panel.background = element_rect(fill = "transparent", colour = NA),
         panel.grid = element_blank(),
         axis.text = element_blank(),
         axis.ticks = element_blank(),
         legend.position =c( "left", "right")) 

gg

Error

Insufficient values in manual scale. 34 needed but only 8 provided.

I dont have R with me now, but try to swap the length(i$import) with the 9 in your brewer.pal command. In general this error means you don't have enough colors or shapes in your scale_fill_manual command.

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