0

我正在尝试在 y 轴上绘制盐度散点图,在 x 轴上绘制日期/时间。但是,当我尝试绘制它时,我的 x 轴数据在数据结束之前被截断。我尝试添加 xlim,但出现错误。见下文

p_OY1 <- ggplot(data = OY1, aes(x=date_time2, y=Salinity)) + geom_point() + ylim=c(0,12) + xlim=c("0019-10-04 00:00:00", "0020-06-10 00:00:00")+ theme_classic()+
  scale_x_discrete("Date", breaks=c("0019-10-04 10:30:00", "0019-11-01 00:00:00", "0019-12-01 00:00:00", "0020-01-01 00:00:00", "0020-02-01 00:00:00",
                                    "0020-03-01 00:00:00","0020-04-01 00:00:00", "0020-05-01 00:00:00", "0020-06-01 00:00:00"),
                   labels=c("10/4/2019", "11/1/2019", "12/1/2019", "1/1/2020", "2/1/2020", "3/1/2020", "4/1/2020", "5/1/2020", "6/1/2020"))+ylab("Salinity")+ggtitle("OY1")

错误:

c("0019-10-04 00:00:00", "0020-06-10 00:00:00") + scale_x_discrete("Date", : 二进制运算符的非数字参数中的错误

OY1 数据

> dput(head(OY1))
structure(list(Site = c("OY1", "OY1", "OY1", "OY1", "OY1", "OY1"
), Date = c("10/4/19", "10/4/19", "10/4/19", "10/4/19", "10/4/19", 
"10/4/19"), Time = structure(c(37800, 39600, 41400, 43200, 45000, 
46800), class = c("hms", "difftime"), units = "secs"), Salinity = c(0.891307674, 
0.960962348, 1.015788098, 1.096679068, 1.191564305, 1.272517514
), Date_time = c("10/4/19 10:30:00", "10/4/19 11:00:00", "10/4/19 11:30:00", 
"10/4/19 12:00:00", "10/4/19 12:30:00", "10/4/19 13:00:00")), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"), problems = structure(list(
    row = 4550L, col = "Salinity", expected = "a double", actual = "#VALUE!", 
    file = "'~/Documents/TAMUG_Thesis/Rollover_Pass_Data/Logger/RP_LoggerData_OY1.csv'"), row.names = c(NA, 
-1L), class = c("tbl_df", "tbl", "data.frame")))

任何人都可以帮忙吗?我已经把这个搞砸了太久了。谢谢!

4

1 回答 1

0

您的示例数据很有帮助,因为它表明该Date_time列具有类字符。这就是为什么scale_x_datetime没有按预期工作的原因。

您可以通过多种方式将其转换为日期时间格式。一是使用lubridate包。您的日期看起来好像是日/月/年,因此您可以使用函数转换日期 + 时间dmy_hms

看看这是否能让你开始。你需要试验date_breaks才能得到你想要的。

library(lubridate)
library(dplyr)
library(ggplot2)

OY1 %>% 
  mutate(dt = lubridate::dmy_hms(Date_time)) %>% 
  ggplot(aes(dt, Salinity)) + 
  geom_point() + 
  scale_x_datetime(date_labels = "%d/%m/%Y")

使用您的示例数据的结果:

在此处输入图像描述

于 2021-07-29T00:30:59.573 回答