我想在R中创建一个绘图,但存在以下问题:我想将日期和时间作为标签添加到每个点。日期和时间在我的Excel工作表的两个单独的列中。到目前为止,我已经尝试过:geom_text(aes(label = time))。 R给我正确的时间,但给我的日期不正确。 R添加当前日期,而不是我的Excel工作表中写入的日期。
编辑:
我的数据如下:
dput(test)
structure(list(date = c("01.08.2018", "01.08.2018", "02.08.2018", "02.08.2018", "03.08.2018", "03.08.2018"),
time = structure(c(1560943664, 1560943687, 1560943741, 1560946280, 1560946323, 1560946383),
class = c("POSIXct", "POSIXt"), tzone = ""),
north = c(6172449.577, 6172438.383, 6172438.596, 6172491.3, 6172492.683, 6172504.024),
east = c(222251.4534, 222251.0842, 222250.4152, 222250.7746, 222256.5543, 222252.3612),
number = c(1L, 1L, 2L, 2L, 3L, 3L)),
row.names = c(NA, -6L),
class = "data.frame")
这是我的代码:
options(stringsAsFactors = FALSE)
input2 <- "C:\\Users\\test.csv"
test<- read.csv(input2, sep=";")
test$time <- as.POSIXct(test$time, format = "%H:%M:%S")
library(ggplot2)
# dput(test)
plot <- ggplot(test, aes(x=east, y=north, size="9", group=number)) +
geom_point() + geom_line(linetype="dashed", size=1) +
geom_text(aes(label=time),hjust=0, vjust=1.5) +
theme(legend.position="none")
print(plot)
答案 0 :(得分:0)
使用substr
和paste
,您可以创建一个新变量,该变量具有date变量的日期和time变量的时间,然后将此新变量用于ggplot
标签。
df <- structure(list(date = c("01.08.2018", "01.08.2018", "02.08.2018", "02.08.2018", "03.08.2018", "03.08.2018"), time = structure(c(1560943664, 1560943687, 1560943741, 1560946280, 1560946323, 1560946383), class = c("POSIXct", "POSIXt"), tzone = ""), north = c(6172449.577, 6172438.383, 6172438.596, 6172491.3, 6172492.683, 6172504.024), east = c(222251.4534, 222251.0842, 222250.4152, 222250.7746, 222256.5543, 222252.3612), number = c(1L, 1L, 2L, 2L, 3L, 3L)), row.names = c(NA, -6L), class = "data.frame")
df <- df %>%
mutate(date = as.Date(date, "%m.%d.%Y")) %>%
mutate(t = substr(time, 12,19)) %>%
mutate(dt = paste(date,t, sep = " "))
ggplot(df, aes(x=east, y=north, size="9", group=number)) +
geom_point() +
geom_line(linetype="dashed", size=1) +
geom_text(aes(label=dt),hjust=0, vjust=1.5) +
theme(legend.position="none")