我尝试使用 R ggplot 绘制数据,但时间标签无法正确显示在 x 轴上。 任何建议将不胜感激。
示例数据如下:
> dput(head(df1,10))
structure(list(activity = c("Running", "Running", "Running",
"Running", "Running", "Running", "Running", "Running", "Running",
"Running"), time = structure(c(-2209064400, -2209064100, -2209063800,
-2209063500, -2209063200, -2209062900, -2209062600, -2209062300,
-2209062000, -2209061700), tzone = "UTC", class = c("POSIXct",
"POSIXt")), level = c(0.0450582956975968, 0.049786810752437,
0.049786810752437, 0.0409378662803991, 0.0373264654807176, 0.0373264654807176,
0.0518442650051548, 0.0471157499503146, 0.0527766243609182, 0.0615719801782924
)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))
数据可以在Excel中正确可视化。
但是我无法在 R 中绘制相同的数据。时间标签未显示 正确地,数据形状看起来也是错误的。
这是我使用的R代码:
df2 <- read_excel("sampledata.xlsx")
ggplot(df2, aes(x = time, y = activity)) + geom_density_ridges2()
您需要使用
scale_x_datetime
以及参数 date_labels = "%I:%M %p"
才能获得与 Excel 相同的输出格式。
但是,
geom_density_ridges
在这里是错误的函数。您在 Excel 中绘制每个 level
的 activity
,而不是 x 轴上的测量密度,这就是形状错误的原因。
使用问题中所示的具有相同基本结构和名称的数据集的近似值,我们可以在 R 中重现 Excel 绘图,如下所示:
library(tidyverse)
df %>%
mutate(activity = factor(activity, c("Walking", "Running"))) %>%
ggplot(aes(time, level, color = activity)) +
geom_line(linewidth = 1) +
facet_wrap(activity ~ ., ncol = 1, scales = "free") +
scale_x_datetime(date_breaks = "1 hour",
date_labels = "%I:%M %p") +
scale_colour_manual(NULL, values = c("deepskyblue4", "orangered")) +
labs(x = NULL) +
theme_bw(16) +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x = element_text(hjust = 1, angle = 45),
strip.background = element_blank(),
strip.text = element_text(size = 20, face = "bold"))