plunderbuss
plunderbuss

Reputation: 77

Making multiple subplots in R

I am very new to R and struggling with something that I know should be simple. I am able to make one scatterplot but would like to make multiple subplots using each feature in my dataset plotted against the variable: per_gop.

My code for one scatter plot is as follows:

data_US@data %>%
  ggplot(aes(x=as.numeric(Hispanic_o), y=as.numeric(per_gop)))+ 
  geom_point(aes(fill=as.numeric(gop_dem), size=as.numeric(total_vote)),colour="#525252",pch=21) +
  stat_smooth(method=lm, se=FALSE, size=1, colour="#525252")+
  scale_fill_distiller(palette="RdBu", type="div", direction=1, guide="colourbar", limits=c(-1,1))+
  theme_bw()+
  theme(legend.position="none")+
  ggtitle(paste("correlation:",round(cor.test(as.numeric(data_US@data$per_gop),as.numeric(data_US@data$Hispanic_o))$estimate,2)))

I have tried using a gather function for this but I am not sure how to correctly pass it to the code for plotting:

My code so far for multiple subplots is as follows:

data_US@data %>%

  gather(c(White_alon,Black_or_A, Asian_alon,Hispanic_o,Foreign_bo,
          Veterans_2,Language_o,Homeowners,Median_val,Per_capita,Bachelors_,
          Private_no), key = "expl_var", value="la_prop") %>%

  ggplot(aes(x=??????, y=per_gop))+ 
  geom_point(aes(fill=gop_dem, size=total_vote),colour="#525252",pch=21) +
  stat_smooth(method=lm, se=FALSE, size=1, colour="#525252")+
  scale_fill_distiller("BrBG", type="div", direction=1, guide="colourbar", limits=c(-1,1))+
  facet_wrap(~expl_var, scales="free")+
  theme_bw()+
  theme(legend.position="none")+ggtitle(paste("correlation:",round(cor.test(data_US@data$per_gop,data_US@data$Persons_65)$estimate,2)))

This is the style of output I am trying to create, just without the repeating variable:

enter image description here

I would be very grateful if someone could point me in the right direction... Thank you!

Upvotes: 1

Views: 219

Answers (1)

Jon Spring
Jon Spring

Reputation: 66415

Here's a reproducible example using the mtcars dataset. Should be possible to apply same form to your data, but hard to know for sure without seeing an example of that data.

library(tidyverse)
mtcars %>%
  gather(expl_var, la_prop, -mpg) %>%
  ggplot(aes(la_prop, mpg)) + 
  geom_point(colour="#525252",pch=21) +
  stat_smooth(method=lm, se=FALSE, size=1, colour="#525252")+
  facet_wrap(~expl_var, scales = "free") +
  theme_bw()+
  theme(legend.position="none")

enter image description here

Upvotes: 2

Related Questions