R 如何对齐共享y轴的地图打印和方框打印
我正在尝试对齐或组合地图和箱线图,它们的y轴都是纬度。我已经找到了很多方法来对齐图,但似乎有一张地图会使事情复杂化。我想让两个图无缝对齐,地图在左边,箱线图在右边 下面是两个绘图的示例代码:R 如何对齐共享y轴的地图打印和方框打印,r,ggplot2,R,Ggplot2,我正在尝试对齐或组合地图和箱线图,它们的y轴都是纬度。我已经找到了很多方法来对齐图,但似乎有一张地图会使事情复杂化。我想让两个图无缝对齐,地图在左边,箱线图在右边 下面是两个绘图的示例代码: library(ggplot2) library(maps) library(gridExtra) ##Plot base map s_map <- map_data('state',region=c('south carolina','georgia','florida')) p <- gg
library(ggplot2)
library(maps)
library(gridExtra)
##Plot base map
s_map <- map_data('state',region=c('south carolina','georgia','florida'))
p <- ggplot() + coord_fixed()
base_world <- p+geom_polygon(data=s_map, aes(x=long, y=lat, group=group), color="white", fill="grey72")
yscale <- c(24:34)
map1 <- base_world +
coord_map(xlim = c(-83, -79.5),ylim = c(25, 34)) +
xlab("") +
ylab("Latitude") +
scale_y_discrete(labels=yscale)
##plot boxplot (seasonal movements of an animal)
df <- data.frame("month"=month.abb,
"min"=c(26,26,26,28,28,29,29,29,28,28,26,26),
"lci"=c(27,27,27,29,29,30,30,30,29,29,27,27),
"med"=c(28,28,28,29,29,31,31,31,29,29,28,28),
"uci"=c(29,29,29,30,30,32,32,32,30,30,29,29),
"max"=c(30,30,30,31,31,33,33,33,31,31,30,30),
"order"=c(1:12))
boxplot1 <- ggplot(df, aes(x=factor(order), ymin = min, lower = lci, middle = med, upper = uci, ymax = max)) +
geom_boxplot(stat = "identity") +
ggtitle("Latitude by Month") +
xlab("Month") +
ylab("Latitude") +
ylim(24,33)
grid.arrange(map1,boxplot1,ncol=2)
库(ggplot2)
图书馆(地图)
图书馆(gridExtra)
##绘制底图
这可能对你有用,我改变了三件事:
- 将
ggtitle(“”)添加到地图中
- 将
主题(plot.margin())
添加到两个绘图中,以更改绘图周围的空间(您可以使用这些值)
- 将
scale_y_continuous(限制=c(24,33),中断=seq(24,33,by=1),扩展=c(0,0))
添加到绘图中,以创建与地图相同的轴比例
map1如果你一次只问一个问题,这个网站效果最好,因为你最多只能接受一个答案。展示完成任务的任何尝试,并准确描述您陷入困境的地方,也很好。堆栈溢出不是代码编写服务。
# build the plots
map2 <- ggplot_gtable(ggplot_build(map1))
boxplot2 <- ggplot_gtable(ggplot_build(boxplot1))
# copy the plot height from p1 to p2
boxplot2$heights <- map2
grid.arrange(map2,boxplot2,ncol=2,widths=c(1,5))
map1 <- base_world +
coord_map(xlim = c(-83, -79.5),ylim = c(25, 34)) +
xlab("") +
ylab("Latitude") +
scale_y_discrete(labels=yscale) +
ggtitle("") +
theme(plot.margin=unit(c(0.5,-1.5,0.5,-8), "cm"))
boxplot1 <- ggplot(df, aes(x=factor(order), ymin = min, lower = lci, middle = med, upper = uci, ymax = max)) +
geom_boxplot(stat = "identity") +
ggtitle("Latitude by Month") +
xlab("Month") +
ylab("Latitude") +
scale_y_continuous(limits=c(24,33), breaks=seq(24,33,by=1), expand=c(0,0)) +
labs(y=NULL) +
theme(plot.margin=unit(c(0.5,0.5,0.5,-6), "cm"))
grid.arrange(map1,boxplot1,ncol=2)