【问题标题】:How to make a horizontal line chart with multiple years in如何制作具有多年历史的水平折线图
【发布时间】:2022-10-06 05:07:51
【问题描述】:

我想制作一个水平折线图,x 轴上有日期,y 轴是治疗,每年的数据有多条线,用于每种治疗的第一朵花的平均儒略日期。我不知道如何使这个情节包括多年。

我想要这样的东西(见下图),但每种治疗类型将有 2 行代表每年。

我还想用年份标记每条水平线,以防我想在情节中添加多年。

我用于上述情节的代码:

ggplot(flwr_avg_duration_19) +
        geom_segment(aes(x = avg_first_flwr, xend = avg_last_flwr, y = treatment_key, yend = treatment_key, color= as.factor(treatment_key)), size = 2) +
        labs(title = \"KBS 2019 Average Flower Duration\", x = \"Julian Date\", y = \"Treatment\") +
        scale_y_discrete(labels=c(\"A0\" = \"Ambient\",
                                  \"AI\" = \"Ambient +\\n Reduced\\n Herbivory\",
                                  \"W0\"=\"Warmed\",
                                  \"WI\"=\"Warmed +\\n Reduced\\n Herbivory\")) +
        theme(legend.position = \"none\")

这是我的数据的一个子集:

dput(flwr_avg_duration_umbs[1:8,])
structure(list(site = c(\"umbs\", \"umbs\", \"umbs\", \"umbs\", \"umbs\", 
\"umbs\", \"umbs\", \"umbs\"), year = c(2016L, 2016L, 2016L, 2016L, 
2017L, 2017L, 2017L, 2017L), state = c(\"ambient\", \"ambient\", 
\"warmed\", \"warmed\", \"ambient\", \"ambient\", \"warmed\", \"warmed\"), 
    treatment_key = c(\"A0\", \"AI\", \"W0\", \"WI\", \"A0\", \"AI\", \"W0\", 
    \"WI\"), insecticide = c(\"no_insects\", \"insects\", \"no_insects\", 
    \"insects\", \"no_insects\", \"insects\", \"no_insects\", \"insects\"
    ), year_factor = c(2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), avg_first_flwr = c(157.5, 
    162.904761904762, 154.76, 160.090909090909, 160.678571428571, 
    161.269230769231, 159.848484848485, 158.695652173913), avg_last_flwr = c(182.384615384615, 
    186.761904761905, 186.64, 186.727272727273, 187.5, 188.423076923077, 
    186.939393939394, 187.608695652174)), row.names = 29:36, class = \"data.frame\")

    标签: r ggplot2


    【解决方案1】:

    您需要position_dodge 才能按年份显示组。使用group 美学来确保您每年都在躲避。您将需要使用geom_linerange 而不是geom_segment,但无论如何这是自然的选择。

    ggplot(flwr_avg_duration_umbs) +
      geom_linerange(aes(xmin = avg_first_flwr, xmax = avg_last_flwr,
                       y = treatment_key, 
                       color = as.factor(treatment_key),
                       group = year), size = 2, 
                     position = position_dodge(width = 0.5)) +
      labs(title = "KBS 2019 Average Flower Duration", 
           x = "Julian Date", y = "Treatment") +
      scale_y_discrete(labels = c("A0" = "Ambient",
                                  "AI" = "Ambient +\n Reduced\n Herbivory",
                                  "W0" = "Warmed",
                                  "WI" = "Warmed +\n Reduced\n Herbivory")) +
      theme_bw() +
      theme(legend.position = "none") 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多