【发布时间】:2022-01-13 17:13:39
【问题描述】:
我的数据集是一个数据框,其中包含过去 4 个夏天的每日最高水温。
X site DateTime value Month Year Day
<int> <fct> <dttm> <dbl> <int> <fct> <chr>
1 6775 RAYNER_UP 2018-07-09 19:00:00 19.8 7 2018 07/10
2 6776 RAYNER_UP 2018-07-10 19:00:00 21.2 7 2018 07/11
3 6777 RAYNER_UP 2018-07-11 19:00:00 20.4 7 2018 07/12
4 6778 RAYNER_UP 2018-07-12 19:00:00 20.1 7 2018 07/13
5 6779 RAYNER_UP 2018-07-13 19:00:00 17.3 7 2018 07/14
6 6780 RAYNER_UP 2018-07-14 19:00:00 19.5 7 2018 07/15
7 6781 RAYNER_UP 2018-07-15 19:00:00 21.2 7 2018 07/16
8 6782 RAYNER_UP 2018-07-16 19:00:00 21.0 7 2018 07/17
9 6783 RAYNER_UP 2018-07-17 19:00:00 19.8 7 2018 07/18
10 6784 RAYNER_UP 2018-07-18 19:00:00 16.8 7 2018 07/19
我的目标是制作一个每年都有不同线条的折线图。到目前为止,在互联网的大力帮助下,我每年都做了一条线,但规模非常拥挤example。
我想重新调整时间序列中的 x 轴以显示月份中的日期。
到目前为止,在 ggplot 中使用 scale_x_datetime 和 scale_x_date 但均未成功。 我不断收到错误消息:输入无效:time_trans 仅适用于 POSIXct 类的对象,即使日期列在 POSIXct 中。
给出问题的代码示例:
test1 = ggplot() +
geom_line(data = Rayner_up_summer, aes(x=strftime(DateTime,format="%m/%d"),
y=value,
group = Year,
color=strftime(DateTime,format="%Y")))+
# size=.1))+
scale_color_discrete(name="Year")+
labs(x="date")
有谁知道为什么即使我的 x 轴 (DateTime) 是 POSIXct 日期时间格式,我也无法使用 scale_x_datetime?如果您有任何建议,我将不胜感激
【问题讨论】:
-
您的代码运行良好。我只能猜测您在尝试将
scale_x_date添加到您的代码时遇到了错误?问题可能是您将DateTime列(属于Date 类)转换为strftime(DateTime,format="%m/%d"),这是一个字符。因此,当添加scale_x_date时会出现错误,只需使用aes(x = DateTime, ..)。如果你想设置标签的格式,你可以通过+ scale_x_date(date_labels = "%m/%d") -
感谢您的回复斯特凡。 strftime(DateTime,format="%m/%d") 是我能够将年份全部绘制在相同的 4 个月范围内的唯一方法,以便它们相互重叠。另外,我错误地发布了错误数据框的示例,我已对其进行了更新,因此它将 DateTime 显示为 POSIXct。