问题描述
我正在尝试使用光栅注释功能将图像叠加在ggplot地图上.我已按照该线程中的说明进行操作如何将图像叠加到ggplot上?,但是我使用的是"ggplot"而不是"qplot"来绘制我的图.
I'm trying to superimpose an image on a ggplot map using the raster annotation function. I've followed the instructions in this thread How do I overlay an image on to a ggplot? , but I'm using "ggplot" instead of "qplot" to plot my figure.
但是,图像要么没有出现在图形上(当我运行绘图函数的前三行:ggplot,geom_polygon和注解栅格时),或者如果我运行整个序列,则会产生此错误:
However, the image either doesn't appear on the figure (when I run the first three lines of the plotting function: ggplot, geom_polygon and annotation_raster), or if I run the whole sequence, this error is produced:
Error in if (nrow(layer_data) == 0) return() : argument is of length zero
我已经尝试了各种各样的方法,因此,如果有人对解决问题有任何想法,我将非常感激!
I've tried all sorts of things so if anyone has any ideas how to solve the problem, I would be extremely grateful!
### Reproducible example
library(png)
library(ggplot2)
#Create data
scores <-c(5,10,-12,20)
area <-c(2630, 3970, 1550, 7485)
lat <- c(-16, -23, -30, -27)
long <- c(132, 143, 120, 140)
data <- as.data.frame(scores)
data[,2] <- as.data.frame(area)
data[,3] <- as.data.frame(long)
data[,4] <- as.data.frame(lat)
colnames(data)<-c("scores","area","lon","lat")
#Load PGN image for raster annotation
mypngfile <- download.file('http://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Rlogo.png/200px-Rlogo.png', destfile = 'mypng.png', mode = 'wb')
mypng <- readPNG('mypng.png')
#Breaks and colours for mapping
brks <- c(-20,-10,0,10,20)
colors <- rev(c(rgb(0,0,0.6),rgb(0,0.6,1),rgb(0,0.8,1),rgb(0.8,1,0.2)))
plot_data <- as.numeric(cut(data$scores,breaks=brks))
col_data <- as.factor(plot_data)
#Map of Australia
Australia<-map_data("world",region = c("Australia", "Australia:Tasmania"))
Oz<-subset(Australia,long>110 & lat>-50 & long<155)
#Create plot
ggplot() +
geom_polygon( data=Oz, aes(x=long, y=lat, group=group), colour="black", fill="grey68") +
annotation_raster(mypng,xmin=120, xmax=130, ymin=-45, ymax=-49) +
geom_point(data=data,aes(x=long,y=lat,color=col_data, size=area),show_guide=F) +
scale_size_area(name="area",max_size=20)
推荐答案
只需稍作更正(我还调整了R徽标的坐标以使其可见):
Just a small correction is required (also I adjusted coordinates for R logo to make it visible):
ggplot(data=Oz, aes(x=long, y=lat)) +
geom_polygon(aes(group=group), colour="black", fill="grey68") +
annotation_raster(mypng, xmin=120, xmax=130, ymin=-37, ymax=-44) +
geom_point(data=data, aes(colour=col_data, size=area), show_guide=F) +
scale_size_area(name="area", max_size=20)
这篇关于Annotation_raster在ggplot中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!