gpt4 book ai didi

r - 将日期刻度添加到 R 中的 ggplot

转载 作者:行者123 更新时间:2023-12-04 09:07:25 26 4
gpt4 key购买 nike

我正在尝试在此图中的 x 轴上添加刻度以显示一年中的所有月份:

enter image description here

我的代码如下:

library(ggplot2)
library(scales)
p <- ggplot(df_test, aes(time, reading))
p + geom_point(alpha = 1/4) + geom_smooth()

我曾尝试使用 scale_x_date但遇到以下错误:
Error: Invalid input: date_trans works with objects of class Date only

这是我正在使用的数据框:
 hour   reading   date                time
1 53 1/1/15 2015-01-01 01:00:00
2 55 1/1/15 2015-01-01 02:00:00
3 56 1/1/15 2015-01-01 03:00:00

我的时间变量的类:

class(df_test$time) "POSIXct" "POSIXt"

最佳答案

使用 scale_x_date(breaks="month", labels=date_format("%b%)) .这是一个例子。

library(quantmod)
sp500 <- getSymbols("SP500", src="FRED", auto.assign=FALSE)
sp500 <- sp500["2015-01-01::"]
sp500 <- data.frame(time=as.POSIXct(index(sp500), origin="1970-01-01"),sp500)
class(sp500$time)
# [1] "POSIXct" "POSIXt"

library(ggplot2)
library(scales) # for date_format(...)
ggplot(sp500, aes(x=as.Date(time), y=SP500))+
geom_line()+
scale_x_date(breaks="month", labels=date_format("%b"))

enter image description here

关于r - 将日期刻度添加到 R 中的 ggplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32601835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com