如何格式化 R 中的轴、年份和月份

发布于 2024-08-14 12:54:17 字数 295 浏览 2 评论 0 原文

我有以下数据集

1890 mar 0.4
1890 apr 0.8
1890 may 1.0
...
1989 jan 0.2
1989 feb 0.4
1989 mar 0.5

如何在 R 中绘制线图,并在 x 轴上绘制年,每 5 年显示一次?

我的问题不在于制作情节,而是只显示我想要的年份,并将它们放在那一年的年初。所以我不想在四月勾选,而是在一月勾选。

I have the following dataset

1890 mar 0.4
1890 apr 0.8
1890 may 1.0
...
1989 jan 0.2
1989 feb 0.4
1989 mar 0.5

How can I make a line plot in R with on the x-axis the year, displayed every 5 years?

My problem is not so much making the plot, but getting to display only the years I want, and place them on the beginning of that year. So I don't want a tick on April but on January.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

_蜘蛛 2024-08-21 12:54:17

这应该可以帮助您开始:

# create some data
set.seed(1)
tmp <- seq(as.POSIXct("1890-03-01", tz="GMT"),
           as.POSIXct("1920-03-01", tz="GMT"),
           by="month")
df <- data.frame(date=tmp,
                 val=rnorm(length(tmp)))

# plot data
plot(df$date, df$val, xaxt="n")
tickpos <- seq(as.POSIXct("1890-01-01", tz="GMT"),
               as.POSIXct("1920-01-01", tz="GMT"),
               by="5 years")
axis.POSIXct(side=1, at=tickpos)

This should get you started:

# create some data
set.seed(1)
tmp <- seq(as.POSIXct("1890-03-01", tz="GMT"),
           as.POSIXct("1920-03-01", tz="GMT"),
           by="month")
df <- data.frame(date=tmp,
                 val=rnorm(length(tmp)))

# plot data
plot(df$date, df$val, xaxt="n")
tickpos <- seq(as.POSIXct("1890-01-01", tz="GMT"),
               as.POSIXct("1920-01-01", tz="GMT"),
               by="5 years")
axis.POSIXct(side=1, at=tickpos)

plot

迟到的我 2024-08-21 12:54:17

默认情况下,使用 zoo 作为绘图,您会得到 rcs (正确!)建议的内容线和同一轴:

R> library(zoo)
R> zdf <- zoo(df$val, order.by=df$date)
R> plot(zdf)
R> 

help(plot.zoo) 示例展示了如何进行更奇特的日期索引,本质上是 rcs 向您展示的内容,但通过附加格式,例如,

R> fmt <- "%Y-%m"  ## year-mon
R> txt <- format(index(zdf), fmt)
R> plot(zdf, xaxt='n')
R> axis(side=1, at=index(zdf), lab=txt)
R> 

如果您将 at< /code> 和 lab 你得到的蜱虫也更少。

You get what rcs (correctly !) suggested by default using zoo as plot with lines and the same axis:

R> library(zoo)
R> zdf <- zoo(df$val, order.by=df$date)
R> plot(zdf)
R> 

The help(plot.zoo) examples show to do fancier date indexing, essentially what rcs showed you but with an additional formatting via, say,

R> fmt <- "%Y-%m"  ## year-mon
R> txt <- format(index(zdf), fmt)
R> plot(zdf, xaxt='n')
R> axis(side=1, at=index(zdf), lab=txt)
R> 

If you subset at and lab you get fewer ticks too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文