如何在 R 中使用 lubridate 小时数制作 ggplot2 散点图?

How can I make a ggplot2 scatter plot using lubridate hours in R?

我有一组小时数(有些大于 24)代表一些学生花在学习上的时间。我想使用 ggplot2 绘制学习时间和考试成绩的散点图。问题是总时间数据采用 lubridate 的时间格式,我该如何使用它进行绘图?示例:

            Name          ID           Total Time  Results
1         Student1      xx-xxxxx-xx    9H 56M 0S   37.58
2         Student2      xx-xxxxx-xx   10H 28M 0S   73.89
3         Student3      xx-xxxxx-xx    6H 40M 0S    4.14
4         Student4      xx-xxxxx-xx    3H 22M 0S   33.44

您的 lubridate Total Time 列表示为句点,不能直接在 ggplot 等工具中绘制。幸运的是,很容易将润滑周期转换为您希望的任何级别(即小时、分钟、秒)的数字对象。

之后,很容易将数字时间维度作为 x 轴,将结果作为 y 轴进行绘图。

以下是您的数据示例:

library(lubridate)

# Replicate your data
example <- data.frame(Name = c("Student1","Student2","Student3","Student4"),
            TotalTime = hms(c("09H 56M 0 S","10H 28M 0S","06H 40M 0S", "03H 22M 0S")),
            Results = c(37.58,73.59,4.14,33.44))

example$TotalTime <- as.numeric(example$TotalTime, "hours")

library(ggplot2)
ggplot(example, aes(TotalTime, Results)) + geom_point()