简体   繁体   English

R ggplot - 用两个轴在同一 plot 中绘制具有子类别的多个变量

[英]R ggplot - ploting multiple variables with sub-categories in the same plot with two axes

I have this data:我有这个数据:

date        area        people_tested    positive_cases positive
2021-12-09  Total       76282.0                402.0000 0.005300000
2021-12-10  Total       84023.0                389.0000 0.004600000
2021-12-09  Total_3da        NA                382.3333 0.004900000
2021-12-10  Total_3da        NA                377.6667 0.004933333
2021-12-09  Paris_3da   75257.4                      NA          NA
2021-12-10  Paris_3da   71553.6                      NA          NA

and I would like to create a plot with a line for each combination.我想创建一个 plot ,每个组合都有一条线。 For example:例如:

  1. Line 1 -> Total / people_tested第 1 行 -> 总计 / people_tested
  2. Line 2 -> Total / positive_cases第 2 行 -> 总计 / positive_cases
  3. Line 3 -> Total / positive第 3 行 -> 总计/正
  4. Line 4 -> Total_3da / positive_cases第 4 行 -> Total_3da / positive_cases
  5. Line 5 -> Total_3da / positive第 5 行 -> Total_3da / 正
  6. Line 6 -> Paris_3da / people_tested第 6 行 -> Paris_3da / people_tested

I would also like for 'people_tested' & 'positive_cases' to be on the same axis and the 'positive' to be on a secondary axis.我还希望“people_tested”“positive_cases”位于同一轴上, “positive”位于辅助轴上。

One way I've thought about doing it is to created a new table with the following format but I was wondering if there is a more simple way to do it:我考虑过的一种方法是创建一个具有以下格式的新表,但我想知道是否有更简单的方法来做到这一点:

date        area                      value 
2021-12-09  Total_people_tested     76282.0                
2021-12-10  Total_people_tested     84023.0  
2021-12-09  Total_positive_cases      402.0
2021-12-10  Total_positive_cases      389.0
etc

Directly on ggplot2, I believe is not possible.直接上ggplot2,相信是不可能的。 One solution is combining a reshape step with facet_grid.一种解决方案是将重塑步骤与 facet_grid 相结合。 Something like:就像是:

library(tidyr)

# reshaping to long form
df_tidy <- df %>%
    pivot_longer(cols = people_tested:positive,
            names_to = “names”,
            values_to_ “value”)

# using ggplot
df_tidy %>% ggplot(aes(x = date, y = value)) +
    geom_line() +
    facet_grid(names ~ area)

I recommend the Wickham's book ggplot2: elegant graphics for data analysis .我推荐Wickham 的书 ggplot2:用于数据分析的优雅图形 It has a plenty of examples to explore!它有很多例子可以探索!

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

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