一个图中的两个图(ggplot2)

时间:2016-12-13 17:33:20

标签: r ggplot2

我想要将两个图组合成一个图。 Plot1显示一个国家内的群体的平均得分,Plot2显示该国家与其他国家相比的相对位置,如国家级平均值所示。 (Plot2也使用黑点标记在Plot1中分析哪个国家/地区以及其余国家/地区的灰点,但这对我的问题并不重要。)

Plot1是重要的情节,Plot2通过提供上下文帮助理解Plot1。这两个图有不同的x和y刻度,所以我删除了Plot2的x轴标签。此外,我在Plot2中调整y轴上的分数(通过添加常数)以避免重叠。 Plot2中的实际得分并不重要,只有国家的相对位置。

总之,我想要Plot1,但是有点和Plot2中的线在Plot1中再现。

我找到了几个讨论两个图集合成一个页面的页面,但没有一个解决了我的问题。

library(ggplot2)

# Within country scores (age-groups)
# -------------------------------------------
age_group<-c("15-19","20-24","25-29","30-34","35-39","40-44","45-49",
         "50-54","55-59","60-64","65-69", "70-74", "75-79", "80-84", "85-89")

scores1<-c(0.000, 0.000, -0.362, -0.546, -0.652, -1.588, -1.333, -1.365, -1.283, -1.394,
       -1.385, -1.622, -1.278, -1.502, -0.909)

within_scores <- data.frame(age_group, scores1)

plot1 <- ggplot(within_scores, aes(age_group, scores1, group = 1)) + geom_point() + 
geom_line() + labs(x = NULL, y = NULL, title="Belgium") + theme_bw() + ylim(-2.2,2) + 
theme(text = element_text(size=8), axis.text.x = element_text(angle=50, hjust=1))

plot1

# Between-country cores (country-level means)
# -------------------------------------------
scores2<-c(-0.429, -0.950, -0.622, 0.000, -0.481, -0.778, -0.657, -1.017, -0.394, -0.546, 
-0.643, -0.844, -0.884, -0.575, -1.079, -0.717, -0.862, -0.481, -0.833, -0.779, -1.577, 
-0.419, -0.255, -0.707, -0.596, -0.283, -1.225, -0.375)


# A constant is added to avoid that the two lines/plots overlap 
scores2 <- scores2 + 1.5 

countries<-c("BE", "BG", "CH", "CZ", "DE", "DK", "EE", "ES", "FI", "FR", "GB", "GR", "HR", 
"HU", "IE", "IL", "LV",  "NL", "NO", "PL", "PT", "RO", "RU", "SE", "SI", "SK", "TR", "UA")
between_scores <- data.frame(countries, scores2)

g1 <- subset(between_scores, countries == "BE")

plot2 <- 
ggplot(between_scores, aes(x=reorder(countries, -scores2), y=scores2, group = 1)) + 
geom_point() + geom_line() + labs(x = NULL, y = NULL, title="Belgium") + 
theme_bw() + ylim(-2,2) + theme(text = element_text(size=8), 
axis.text.x = element_text(angle=50, hjust=1)) + geom_point(colour="grey") + 
geom_line(colour="grey") + geom_point(data=g1, colour="black") + 
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), 
axis.ticks.x=element_blank())

plot2

0 个答案:

没有答案