首页 > 解决方案 > 如何在绘图的 Y 轴上的每个点上添加三个条形

问题描述

我想绘制一个重要的三向交互。这三个因素是收集、品种和灌溉,响应变量是 meanGlucCVI。我目前的想法(对其他建议持开放态度)是制作一个条形图,其中 Y 轴上的 meanGlucCVI 响应和 X 轴上的灌溉。在 X 轴上的每个灌溉处理处,每个收集处理都会有一个条形图。最后,我会为每个品种制作这些图表之一。

我的问题是我不知道如何将三个收集栏添加到我的情节中。我已经多次看到类似这样的图表,但我对 R 的理解还不够扎实,无法实现。

这似乎是显示这些数据的明智方式吗?如果是这样,我该如何为它编写代码?我认为 usingggplot及其facetwrap功能可能是有意义的,或者可能只是ggplot用于单个图形并将它们与gridExtrabase R 结合起来(如果可能的话。)

这是我当前的数据集:

dput(head(dataAvgGlucCVI))


structure(list(Collection = structure(c(1L, 1L, 1L, 1L, 1L, 1L
), .Label = c("1", "2", "3"), class = "factor"), Variety = structure(c(1L, 
1L, 1L, 1L, 1L, 2L), .Label = c("Hodag", "Lamoka", "Snowden"), class = "factor"), 
    Irrigation = structure(c(1L, 2L, 3L, 4L, 5L, 1L), .Label = c("Rate1", 
    "Rate2", "Rate3", "Rate4", "Rate5"), class = "factor"), meanGlucCVI = c(0.03475, 
    0.03475, 0.0455, 0.047, 0.061, 0.04275)), row.names = c(NA, 
-6L), groups = structure(list(Collection = structure(c(1L, 1L
), .Label = c("1", "2", "3"), class = "factor"), Variety = structure(1:2, .Label = c("Hodag", 
"Lamoka", "Snowden"), class = "factor"), .rows = list(1:5, 6L)), row.names = c(NA, 
-2L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame")) 

标签: rggplot2statistics

解决方案


我不完全理解应该将哪个变量映射到确切的内容,但这是第一步,实际上是得到一个图。如果您发现自己编写代码很困难,您可以就您希望更改的内容提供反馈。假设df由 生成df <- structure(your_dput_output)

library(ggplot2)

# I'm including a second factor for illustration purposes.
df2 <- df
df2$Collection <- as.factor(2)
# I'm reversing the order of the response to visually distinguish them
df2$meanGlucCVI <- rev(df2$meanGlucCVI)

# Now I'll combine them
df <- rbind(df, df2)

# You give ggplot the data.frame, and map inside aes() what 
# variable you want to map to what aesthetic.
ggplot(df, aes(x = Irrigation, y = meanGlucCVI, fill = Collection)) +
  # We'll dodge the groups (determined by fill) so that they are not stacked
  geom_col(position = position_dodge(width = 0.7), width = 0.6) +
  # You can facet on a variable, for example Variety
  facet_wrap(~ Variety)

在此处输入图像描述


推荐阅读