我无法通过检查以前的问题来找到解决方案,所以我想把这个扔在这里。
我有一个Excel文件,其标题为“ Date”和“ Tensiometer”。请务必注意,日期另存为d/mm/yyyy
。
我正在尝试使用ggplot
来制作一个在x轴上带有日期并在y轴上带有张力计读数的图形。当我输入时,日期的值是1)非常大的整数(43275、43300等)和2)不在x轴的每个刻度上。这些值是按时间顺序排列的,只是没有显示正确的数字。
这是我到目前为止的代码
library(openxlsx)
library(ggplot2)
read.xlsx(file.choose("file that I'm using"))
df <-read.xlsx(file.choose("file that I'm using"))
ggplot(data = df) + geom_point(mapping = aes(x = Date, y = Tensiometer))
下面是数据的示例:
structure(list(Plot = c(1046, 1013, 1082, 1095, 1163, 1046),
Treatment = c(5, 3, 2, 4, 1, 5), Date = c(43258, 43258, 43258,
43258, 43258, 43264), Time = c(0.425694444444444, 0.425694444444444,
0.425694444444444, 0.425694444444444, 0.425694444444444,
0.394444444444444), Tensiometer = c(19, 13, 20, 12, 20, 34
)), row.names = c(NA, 6L), class = "data.frame")
不过,我目前仅对绘制“日期”和“张力计”感兴趣。 任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
如果您知道日期是否代表1900(或1904)之后的日期,则只需将Date字段添加到开始日期即可获得日期。例如,使用保存为df
的示例数据:
df<-structure(list(Plot = c(1046, 1013, 1082, 1095, 1163, 1046),
Treatment = c(5, 3, 2, 4, 1, 5),
Date = c(43258, 43258, 43258, 43258, 43258, 43264),
Time = c(0.425694444444444, 0.425694444444444,
0.425694444444444, 0.425694444444444, 0.425694444444444,
0.394444444444444),
Tensiometer = c(19, 13, 20, 12, 20, 34)),
row.names = c(NA, 6L), class = "data.frame")
df <- df %>% mutate(Date_Structured = as.Date("1900-01-01")+Date)
礼物:
## Plot Treatment Date Time Tensiometer Date_Structured
## 1 1046 5 43258 0.4256944 19 2018-06-09
## 2 1013 3 43258 0.4256944 13 2018-06-09
## 3 1082 2 43258 0.4256944 20 2018-06-09
## 4 1095 4 43258 0.4256944 12 2018-06-09
## 5 1163 1 43258 0.4256944 20 2018-06-09
## 6 1046 5 43264 0.3944444 34 2018-06-15
此外,我们可以为同一日期的每个事件创建一个观察ID:
df$Date_Obs <-
ave(as.character(df$Date_Structured),
as.character(df$Date_Structured),
FUN=seq_along)
这给出了以下内容:
## Plot Treatment Date Time Tensiometer Date_Structured Date_Obs
## 1 1046 5 43258 0.4256944 19 2018-06-09 1
## 2 1013 3 43258 0.4256944 13 2018-06-09 2
## 3 1082 2 43258 0.4256944 20 2018-06-09 3
## 4 1095 4 43258 0.4256944 12 2018-06-09 4
## 5 1163 1 43258 0.4256944 20 2018-06-09 5
## 6 1046 5 43264 0.3944444 34 2018-06-15 1
从那里,我们可以在同一日期的同一条上绘制每个观测值,但是颜色不同,以便能够使用fill = Date_Obs
来区分它们。我使用width = 1
来减少条形与其他日期的重叠,然后使用scale_x_date()
来显示两次出现之间的每一天。最后,我在x轴上旋转标签,以便于阅读:
df %>%
ggplot(aes(x = Date_Structured, y = Tensiometer, fill = Date_Obs))+
geom_bar(stat="Identity",width = 1) + # Making the bars fall only cover the date they correspond to
scale_x_date(date_labels="%m-%d-%Y", date_breaks ="1 day") + # Adding each date to x-axis
theme(axis.text.x = element_text(angle = 65, hjust = 1))