简体   繁体   中英

Cleaner way to plot multiple bar charts of different outcome variables (R)

I am wondering if there is a better way to produce 4 barcharts of different outcome variables arranged in a grid:

This is the code I used:

library(cowplot)

bar1 <- ggplot(data = subset(data, !is.na(MHQ_Heading_Male_Quartile))) +
  geom_bar(mapping = aes(x = MHQ_Heading_Male_Quartile))
bar2 <- ggplot(data = subset(data, !is.na(AHQ_Heading_Male_Quartile))) +
  geom_bar(mapping = aes(x = AHQ_Heading_Male_Quartile))
bar3 <- ggplot(data = subset(data, !is.na(MHQ_Heading_Female_Quartile))) +
  geom_bar(mapping = aes(x = MHQ_Heading_Female_Quartile))
bar4 <- ggplot(data = subset(data, !is.na(AHQ_Heading_Female_Quartile))) +
  geom_bar(mapping = aes(x = AHQ_Heading_Female_Quartile))

plot_grid(bar1, bar2, bar3, bar4, ncol = 2)

However, there is a lot of repeated code- is there some function or way to create the same plot with ggplot2 in fewer lines?

I would convert relevant columns from wide to long (the ones ending in "_Quartile" ) and then use facet_wrap to show the 4 plots in a 2x2 grid with scales = "free" .

Something like this:

data %>%
    gather(key, value, ends_with("Quartile")) %>%
    filter(!is.na(value)) %>%
    ggplot(aes(value)) +
    geom_bar() +
    facet_wrap(~ key, scales = "free", ncol = 2, nrow = 2)

在此处输入图片说明

As mentioned you need to make it a long format using dplyr gather (or reshape package) and then facet over this.

`data %>%
  select( MHQ_Heading_Male_Quartile, AHQ_Heading_Male_Quartile, MHQ_Heading_Female_Quartile, AHQ_Heading_Female_Quartile) %>%
  gather("Type", "Range", MHQ_Heading_Male_Quartile:AHQ_Heading_Female_Quartile) %>%
  filter(!is.na(Range)) %>%
  ggplot(aes(x=Range)) + 
  geom_bar() + 
  facet_wrap(~Type, scales="free")`

I'll leave it to you to clean the graphs up but that's the basic premise.

Extract the column names to be shown into nms and then for each one use qplot to create a ggplot object so that bars is a list of such objects. Then run plot_grid on that.

nms <- grep("Quartile", names(data), value = TRUE)
bars <- lapply(nms, function(nm) qplot(na.omit(data[[nm]]), xlab = nm))
do.call("plot_grid", bars)

屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM