【问题标题】:Reproduce a plot using ggplot & data wrangling使用 ggplot & data wrangling 重现绘图
【发布时间】:2021-11-17 13:11:40
【问题描述】:

我有一个如下所示的数据集

# # A tibble: 94 × 4
#    type          shortcut    date              time
#    <chr>         <chr>       <date>            <dbl>         
#  1 Three lap      No         2010-08-17         24.24                          
#  2 Three lap      No         2010-08-24         38                             
#  3 Three lap      Yes        2010-08-31         32.4                             
#  4 Single lap     No         2010-09-07         20.6                           
#  5 Single lap     No         2010-09-14         39.03                          

我想重现照片中的情节

我不知道如何重新创建图中的“Race”变量。我试过了,但它不起作用!

newdata <- records %>%
 group_by(type, shortcut) %>%
 mutate(race = case_when( 
                 type == "Three lap" && shortcut == "No" ~ "Three lap with no shortcut",
                 type == "Three lap" && shortcut == "Yes" ~ "Three lap with shortcut",
                 type == "Single lap" && shortcut == "No" ~ "Single lap with no shortcut",
                 type == "Single lap" && shortcut == "Yes" ~ "Single lap with shortcut")) 

ggplot(data = newdata, mapping = aes(x = date, y = time, color = race)) +
  geom_line() + 
  geom_point()

对我应该尝试什么有什么建议吗?

【问题讨论】:

  • 如果您通过包含可用格式的数据来使您的问题可重现,例如将dput(records) 的输出粘贴到问题中以启用对可能解决方案的测试和验证,则更容易为您提供帮助。 Link for guidance on asking questions

标签: r ggplot2 group-by dplyr data-wrangling


【解决方案1】:

使用&amp; 而不是&amp;&amp;,因为&amp;&amp; 用于标量。此外,这里不需要group_by

试试-

library(dplyr)
library(ggplot2)

records %>%
  mutate(race = case_when( 
    type == "Three lap" & shortcut == "No" ~ "Three lap with no shortcut",
    type == "Three lap" & shortcut == "Yes" ~ "Three lap with shortcut",
    type == "Single lap" & shortcut == "No" ~ "Single lap with no shortcut",
    type == "Single lap" & shortcut == "Yes" ~ "Single lap with no shortcut",
    TRUE ~ "Single lap with shortcut"))  %>%
  ggplot(aes(x = date, y = time, color = race)) +
    geom_line() + 
    geom_point()

【讨论】:

  • 嗨@Ronak Shah,我已经尝试了代码并且有一条错误消息:“错误:必须从色调调色板中请求至少一种颜色。” ?我不确定为什么需要指定颜色?
  • 对不起,我没有在 Threelap 和其他值中添加空格。尝试在三和一圈之间有空格的更新答案。
猜你喜欢
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 2023-01-07
  • 1970-01-01
  • 2020-10-18
  • 2021-11-30
相关资源
最近更新 更多