gpt4 book ai didi

r - 如何使用基本 R 图为数据中不存在的日期添加轴刻度

转载 作者:行者123 更新时间:2023-12-01 12:39:19 25 4
gpt4 key购买 nike

我在 base R 中创建了一个图,其中 x 轴基于日期(月)。在某些情况下,我一个月都没有数据,所以跳过了 x 轴上的刻度线,但这看起来很糟糕。有没有办法在 R 中的另外两个刻度点中间画一个刻度?

这是我的情节的一个例子:

month<-c("2010-08-01", "2010-09-01", "2010-10-01", "2010-12-01", "2011-01-01", "2011-02-01",
"2011-03-01", "2011-04-01", "2011-05-01", "2011-06-01", "2011-07-01", "2011-09-01",
"2011-11-01", "2012-01-01", "2012-02-01", "2012-03-01", "2012-05-01", "2012-07-01",
"2012-08-01")
prevalence<-c(10,7.5,5.2,3.5,6.4,2.7,5.8,13.2,4.3,4.7,6.4,4.4,5.2,3.3,1.0,3.1,9.9,33.3,1.0)
df<-data.frame(month, prevalence)
df$month<-as.Date(df$month)

plot(df$month, df$prevalence,lwd = 1.8, ylim=c(0,40),pch=16, bty='n',
ylab="Prevalence (%)", xlab="Month",col='black',cex=1,cex.lab=1.0,cex.axis=1.0)

axis(side = 1, at = df$month, labels=F, tck=-0.015)
axis(side=2, at=c(0,10,20,30,40,50), labels=c("", "", "", "", "", ""), tck=-0.015)

lines(df$month, df$prevalence, col='black', lwd=1.8)

生成的图表:enter image description here

关于同一张图,我问了一个不同的问题,我希望将其作为两个单独的问题发布是合适的。

最佳答案

因为您的 x 值属于 Date 类,您可以使用 seq.Date 生成一个规则的日期序列,它可以用作 at 值,即要绘制刻度线的位置(参见 ?seq.Date?axis.Date 中的示例)。

at <- seq(from = min(df$month), to = max(df$month), by = "month")

然后尝试仅使用刻度线而不使用标签的绘图:

plot(prevalence ~ month, data = df, type = "b")
axis.Date(side = 1, at = at, labels = FALSE)

enter image description here

此外,axis.Date 可让您轻松地格式化 日期。在这里,我通过使用 xaxt 参数禁止在 plot 调用中绘制 x 轴。然后,我添加具有所需 at 位置和 format 的轴,例如%y-%m(年份不带世纪破折号两位数月份)

plot(prevalence ~ month, data = df, type = "b", xaxt = "n")
axis.Date(side = 1, at = at, format = "%y-%m")

enter image description here

有关日期/时间格式的其他可能规范,请参阅 ?strptime

关于r - 如何使用基本 R 图为数据中不存在的日期添加轴刻度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26506417/

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