首页>Program>source

我正在尝试制作一个具有多个因素分组的条形图. excel中我尝试创建的一个示例,按品种和灌溉处理分组:

我知道我可以使用 facet_wrap()生成多个图形 ,但是我想针对多年的相似数据为这种相同类型的数据生成多个图表.我在此示例中使用的数据示例:

Year        Trt Variety    geno yield   SE
2010-2011   Irr Variety.2   1   6807    647
2010-2011   Irr Variety.2   2   5901    761
2010-2011   Irr Variety.1   1   6330    731
2010-2011   Irr Variety.1   2   5090    421
2010-2011   Dry Variety.2   1   3953    643
2010-2011   Dry Variety.2   2   3438    683
2010-2011   Dry Variety.1   1   3815    605
2010-2011   Dry Variety.1   2   3326    584

是否可以在ggplot2中创建多个分组? 我已经搜索了很长时间,但还没有看到类似上面的示例图的示例。

感谢您的帮助!

最新回答
  • 2021-1-11
    1 #

    这可能是一个开始.

    dodge <- position_dodge(width = 0.9)
    ggplot(df, aes(x = interaction(Variety, Trt), y = yield, fill = factor(geno))) +
      geom_bar(stat = "identity", position = position_dodge()) +
      geom_errorbar(aes(ymax = yield + SE, ymin = yield - SE), position = dodge, width = 0.2)
    

    Update: labelling of x axis
    我添加了:
    coord_cartesian ,以设置y轴的限制,主要是下限,以避免默认的轴扩展。
    annotate ,以添加所需的标签.我已经对 x进行了硬编码 位置,在这个相当简单的示例中,我觉得还可以。
    theme_classic ,以删除灰色背景和网格。 theme ,增加较低的print边距,以便为两行标签留出空间,并删除默认标签。
    最后一组代码:由于文本被添加到x轴下方,因此它"消失"在绘图区域之外,因此我们需要删除"剪切".就是这样!

    library(grid)
    g1 <- ggplot(data = df, aes(x = interaction(Variety, Trt), y = yield, fill = factor(geno))) +
      geom_bar(stat = "identity", position = position_dodge()) +
      geom_errorbar(aes(ymax = yield + SE, ymin = yield - SE), position = dodge, width = 0.2) +
      coord_cartesian(ylim = c(0, 7500)) +
      annotate("text", x = 1:4, y = - 400,
               label = rep(c("Variety 1", "Variety 2"), 2)) +
      annotate("text", c(1.5, 3.5), y = - 800, label = c("Irrigated", "Dry")) +
      theme_classic() +
      theme(plot.margin = unit(c(1, 1, 4, 1), "lines"),
           axis.title.x = element_blank(),
           axis.text.x = element_blank())
    # remove clipping of x axis labels
    g2 <- ggplot_gtable(ggplot_build(g1))
    g2$layout$clip[g2$layout$name == "panel"] <- "off"
    grid.draw(g2)
    

  • PHP date()和strtotime()在31日返回错误的月份
  • iis:如何在ASPNET中的多个子域之间共享会话?