使用facet_wrap函数将3个图绘制到同一张图中

时间:2020-10-27 22:00:47

标签: r ggplot2

有人可以向我解释如何使用facet_wrap中的ggplot层在同一张图中绘制3个图,以便每个图应连续排列并缩放每个图的自由更改。

这是我制作的3张图,因为我想查看以下三个协变量之间的关系:median_incomepct_immigrantincome_inequality和Marine Le Pen的投票百分比个别地。 确切地说,这三个协变量不是变量,这就是为什么我必须首先过滤数据帧elections_2017_long_metrop_covariates_lepen_long以便仅保留变量covariates中的每个观察值的原因

此外,如果您有任何建议可以改善图形的可视化效果

graph1 = filter(elections_2017_long_metrop_covariates_lepen_long, covariates == "pct_immigrant")       
ggplot(graph1,aes(x = value,y = pct_votes)) + geom_point(size = 3, alpha = 0.5,colour = "#d90502") + expand_limits(x = 0, y = 0:100) +labs(x = "share of immigrants",y = "percentage of votes for Marine Le Pen")

enter image description here

graph2 = filter(elections_2017_long_metrop_covariates_lepen_long, covariates == "income_inequality")       
ggplot(graph2,aes(x = value,y = pct_votes)) + geom_point(size = 3, alpha = 0.5,colour = "#d90502") + expand_limits(x = 0, y = 0:100) +labs(x = "income inequality",y = "percentage of votes for Marine Le Pen")

enter image description here

graph3 = filter(elections_2017_long_metrop_covariates_lepen_long, covariates == "median_income")  
ggplot(graph2,aes(x = value,y = pct_votes)) + geom_point(size = 3, alpha = 0.5,colour = "#d90502") + expand_limits(x = 0, y = 0:100) +labs(x = "median income",y = "percentage of votes for Marine Le Pen") 

enter image description here

2 个答案:

答案 0 :(得分:0)

您没有提供完整的可复制示例,但我认为这应该对您有用。

要进行构面,应将filter变量传递到facet_wrap()函数中。

elections_2017_long_metrop_covariates_lepen_long %>% 
  filter(covariates %in% c('pct_immigrant', 'median_income', 'income_inequality')) %>% 
  ggplot(aes(x = value,y = pct_votes)) +
  geom_point(alpha = 0.5) +
  facet_wrap(~covariates)

答案 1 :(得分:0)

考虑颜色的完整解决方案可以是:

library(ggplot2)
#Plot
ggplot(subset(elections_2017_long_metrop_covariates_lepen_long
              covariates %in% c('pct_immigrant', 'median_income', 'income_inequality')),
       aes(x = value,y = pct_votes,color=covariates))+
  geom_point(size = 3, alpha = 0.5)+
  expand_limits(x = 0, y = 0:100) +
  labs(x = "share of immigrants",y = "percentage of votes for Marine Le Pen")+
  facet_wrap(.~covariates,scales = 'free',ncol = 1)+
  scale_color_manual(values=rep("#d90502",3))

或者:

library(dplyr)
library(ggplot2)
#Code 2
elections_2017_long_metrop_covariates_lepen_long %>%
  filter(covariates %in% c('pct_immigrant', 'median_income', 'income_inequality')) %>%
  ggplot(aes(x = value,y = pct_votes,color=covariates))+
  geom_point(size = 3, alpha = 0.5)+
  expand_limits(x = 0, y = 0:100) +
  labs(x = "share of immigrants",y = "percentage of votes for Marine Le Pen")+
  facet_wrap(.~covariates,scales = 'free',ncol = 1)+
  scale_color_manual(values=rep("#d90502",3))

没有数据显示缺少输出。