在恒定高度下安排ggplot多个对象

时间:2013-07-31 21:36:49

标签: r ggplot2

我正在尝试将美国地图分成多个窗口(其中一些窗口包含两次相同的状态)。我希望比例是恒定的(这样地图不会失真),但也可以最小化地图之间的空间。我不能使用facet_wrap(由于区域的重叠性质 - 并且无论如何,facet_wrap不能具有固定的比例并且每个窗口具有不同的xlim)。关于如何改善结果间距的任何建议?

require(data.table)
require(ggplot2)
require(maps)
require(gridExtra)
all_states <- as.data.table(map_data("state"))

setnames(all_states,"region","state")

##define regions with overlapping states
weco.states <- c("oregon","washington","california")
west.states <- c("washington","montana", "idaho","utah","nevada","arizona","new mexico",
    "wyoming","colorado","south dakota","texas")
east.states <- c(setdiff(unique(all_states$state), union(weco.states,west.states)),
    "texas","south dakota")
all_states[,c("weco","west","east"):=FALSE]
all_states[state%in% weco.states, weco:=TRUE]
all_states[state%in% west.states, west:=TRUE]
all_states[state%in% east.states, east:=TRUE]


p.regbase <- ggplot() + coord_equal() +ylim(c(25,50))
p.weco <- p.regbase + geom_polygon(data=all_states[(weco),], aes(x=long, y=lat, group = group),colour="white", fill="grey" ) 
p.west <- p.regbase + geom_polygon(data=all_states[(west),], aes(x=long, y=lat, group = group),colour="white", fill="grey" )  
p.east <- p.regbase + geom_polygon(data=all_states[(east),], aes(x=long, y=lat, group = group),colour="white", fill="grey" )  

print(arrangeGrob(p.weco,p.west,p.east,ncol=3,nrow=1))

取决于我在Windows GUI中调整图形窗口大小的方式,结果要么不好(比例不同) enter image description here

或体面(相同的高度)但是空间太大:我怎样才能摆脱多余的空间?

enter image description here

2 个答案:

答案 0 :(得分:5)

让我们澄清一些事情。

  • grid.arrange没有“添加填充”,它只是将网格并排放置在网格布局中。您可以更改行中每个单元格的宽度,

grid.newpage()
pushViewport(viewport(width=5, height=2.5, default.units="in")); 
gt = grobTree(rectGrob(), circleGrob()) 
grid.arrange(gt, gt, gt, nrow=1, newpage=FALSE,
             widths = unit(c(1, 2, 3), "null"))
upViewport()

enter image description here

  • 当它们没有固定的纵横比时,例如对齐图很容易。使用gtable ::: cbind_gtable

  • 固定宽高比通过相对空网格单位在gtable中编码,您可以随时查看,


g = ggplotGrob(p.weco)
g[["heights"]][3] # 2.37008405379269 is the aspect ratio for that plot panel

  • 设置宽度与固定纵横比ggplot2不能正常工作的原因有两个:i)很难猜出我们应该分配的相对宽度,因为这取决于根据数据范围; ii)设备宽度和高度也应根据三个纵横比设置,以避免额外的空白(保持正确的纵横比所必需)

这些问题have been discussed here;我不知道一个优雅而通用的解决方案。

答案 1 :(得分:5)

以下是使用facet_grid()和稍微模糊的设置theme(aspect.ratio=1)的解决方案。情节并不完美,但我希望它能为您提供所需的大部分内容。请注意,状态看起来比它们应该宽一些。显然,1度纬度与美国1度经度的距离明显不同。

# Create a new factor column for faceting.
newfactor = ifelse(all_states$weco, "weco", 
                           ifelse(all_states$west, "west", "east"))

# Manually specify sort order of factor levels.
newfactor = factor(as.character(newfactor), levels=c("weco", "west", "east"))

all_states$region = newfactor

plot_1 = ggplot(all_states, aes(x=long, y=lat, group=group)) + 
         geom_polygon(colour="white", fill="grey") + 
         facet_grid(. ~ region, space="free", scales="free") + 
         theme(aspect.ratio=1)

ggsave("plot_1.png", plot=plot_1, height=4, width=8, dpi=150)

enter image description here