简体   繁体   English

绘制不同结果变量(R)的多个条形图的更简洁方法

[英]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: 我想知道是否有更好的方法来产生以网格形式排列的4个不同结果变量的条形图:

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? 但是,有很多重复的代码-是否有一些函数或方法用ggplot2在更少的行中创建相同的图?

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" . 我会将相关的列从宽转换为长(以"_Quartile"结尾的"_Quartile" ),然后使用facet_wrap在2x2的scales = "free"网格中显示4个图。

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. 如前所述,您需要使用dplyr收集(或重塑包装)将其制成长格式,然后对此进行分面。

`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. 提取要显示为nms的列名称,然后对于每个列使用qplot创建ggplot对象,以便bars是此类对象的列表。 Then run plot_grid on that. 然后在plot_grid上运行plot_grid

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

屏幕截图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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