【问题标题】:layer two ggplot maps on top of each other将两个 ggplot 地图叠加在一起
【发布时间】:2020-02-14 15:31:00
【问题描述】:

我有两个 ggplot 地图,它们都使用相同的 shapefile。一个是数据,另一个是每个国家的名称。目前它们位于单独的 ggplots 中,但如何在现有的(plot1)顶部添加名称?

cnames <- aggregate(cbind(long, lat) ~ region, data=map, 
                    FUN=function(x)mean(range(x)))
names <-ggplot(map, aes(long, lat)) +  
    geom_polygon(aes(x = long, y = lat, group=group), colour='black', fill=NA) +
    geom_text(data=cnames, aes(long, lat, label = region), size=2) +
    coord_map()

plot1 <- ggplot(map, aes(x=long,y = lat, group = group, fill = map$`data`)) + geom_polygon(colour="black") + coord_map("polyconic") + labs(fill = "data") + theme(axis.title.x=element_blank(),axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),axis.title.y=element_blank(),axis.text.y=element_blank(),axis.ticks.y=element_blank())
  plot1 <- plot1 + ggtitle("data")
  plot1 <- plot1 + scale_fill_gradient2(low = muted("grey"), high = muted("deepskyblue4"))

【问题讨论】:

  • 和你上一个问题一样,你能加一个reproducible example吗?很难知道你在使用什么,你有我之前提到的容易出错的 $ 语法,而且我们看不到任何输出,所以不清楚你到底有什么以及你想要改变什么
  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。一般来说,如果您想要一个图,您应该添加层到单个绘图对象,而不是创建多个绘图对象。

标签: r ggplot2 maps layer


【解决方案1】:

我想你可以像这样将图层添加在一起:

invisible(lapply(c("ggplot2", "scales", "mapproj"), require, character.only = TRUE))
#> Loading required package: ggplot2
#> Loading required package: scales
#> Loading required package: mapproj
#> Loading required package: maps
map <- map_data("state")

cnames <- aggregate(cbind(long, lat) ~ region, data=map, 
    FUN=function(x)mean(range(x)))

    ggplot(map, aes(
        x = long,
        y = lat,
        group = group,
        fill = as.numeric(factor(map$region))
    )) + 
    scale_fill_gradient2(low = muted("grey"), high = muted("deepskyblue4"))+
    geom_polygon(colour = "black") +
    geom_text(data=cnames, aes(long, lat, label = region), size=2, inherit.aes = FALSE) +
    coord_map("polyconic") + 
    labs(fill = "region") + 
    theme(
        axis.title.x = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.title.y = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks.y = element_blank()
    ) + 
    ggtitle("data")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多