【问题标题】:Annotation_raster not working in ggplotAnnotation_raster 在 ggplot 中不起作用
【发布时间】:2014-03-14 14:35:16
【问题描述】:

我正在尝试使用光栅注释功能在 ggplot 地图上叠加图像。我已按照此线程 How do I overlay an image on to a ggplot? 中的说明进行操作,但我使用“ggplot”而不是“qplot”来绘制我的图。

但是,图像要么没有出现在图形上(当我运行绘图函数的前三行:ggplot、geom_polygon 和 annotation_raster),或者如果我运行整个序列,就会产生这个错误:

Error in if (nrow(layer_data) == 0) return() : argument is of length zero

我已经尝试了各种方法,如果有人对如何解决问题有任何想法,我将非常感激!

### 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 ggplot2


    【解决方案1】:

    只需要稍作修正(我还调整了 R 标志的坐标使其可见):

    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)
    

    【讨论】:

    • 你应该提到你改变了什么。显然 annotate_raster 将不起作用,除非您在第一次调用 ggplot 时绘制一些东西(即ggplot(data.frame(x=1,y=1), aes(x=x, y=y)) 将起作用但ggplot() 不会)。我花了一些时间来弄清楚这一点。致谢 cmets here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2017-04-19
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多