【问题标题】:X-axis labels bunched together in R plotX 轴标签在 R 图中聚集在一起
【发布时间】:2018-04-10 04:29:46
【问题描述】:

我正在使用 R 绘制值,并尝试用我自己的替换 x 轴标签,如下所示:

plot(date, value, xaxt="n", xlab="Year", ylab="value")
axis(1, at=seq(min(year), max(year), by=10))

其中 min(year) = 1969 和 max(year) = 2016。

绘图本身看起来不错,但 x 轴刻度标签不是:

如您所见,x 轴刻度全部聚集在一起,而不是均匀分布在 x 轴上并且只显示其中一年。

我错过了什么?

谢谢!!

我的源数据如下所示:

 site year       date  value
1  MLO 1969 1969-08-20 323.95
2  MLO 1969 1969-08-27 324.58
3  MLO 1969 1969-09-02 321.61
4  MLO 1969 1969-09-12 321.15
5  MLO 1969 1969-09-24 321.15
6  MLO 1969 1969-10-03 320.54

值是:

date <- data[["date"]]
value <- data[["value"]]
year <- data[["year"]]

【问题讨论】:

  • 什么是min(date)max(date)?他们的班级是什么?
  • > min(year) [1] 1969 > max(year) [1] 2016 > class(min(year)) [1] "integer"
  • 日期:是字符串“1969-08-20”等的数据框,日期类为“因子”
  • 基本上我试图在 x 轴上获得有意义的刻度标签;如果我只是将它留给 plot(),则不会发生任何好事,因为它们是字符串,而且它们太多了。另一种选择可能是尝试将“日期”帧值转换为实际的 R 日期,看看它是否做得更聪明......
  • 可以加head(data),让我们看看你的dataframe是什么样子的。

标签: r plot


【解决方案1】:

一个问题是您将日期的factors 视为它们在数字上是相关的。在内部,factor 只是一个integer,这意味着它们按顺序绘制很方便,但并不反映实际$dates 之间的有效分隔。

相反,将它们转换为实际的Date 对象并使用它。 (由于数据小,我稍微改了一下数据)

dat <- read.table(text='site year       date  value
  MLO 1969 1965-08-20 323.95
  MLO 1969 1968-08-27 324.58
  MLO 1969 1970-09-02 321.61
  MLO 1969 1972-09-12 321.15
  MLO 1969 1979-09-24 321.15
  MLO 1969 1983-10-03 320.54', header=TRUE, stringsAsFactors=FALSE)
dat$date <- as.Date(dat$date, format='%Y-%m-%d')

从这里开始,(主要)你的情节。

plot(value ~ date, data=dat, type='b', xaxt="n", xlab="Year", ylab="value")
years <- as.Date(format(range(dat$date), "%Y-01-01"))
years <- seq(years[1], years[2], '5 years')
str(years)
#  Date[1:4], format: "1965-01-01" "1970-01-01" "1975-01-01" "1980-01-01"
axis(1, at=years, labels=format(years, '%Y'))
# or more directly (thanks @thelatemail)
axis.Date(1, years, format="%Y")

我同时使用atlabels 的原因是,我们可以获得完整的Date 对象的值/位置,同时保留仅年份的打印格式。

【讨论】:

  • 您也可以通过axis.Date(1, years, format="%Y") 直接使用format= 选项。
  • @r2evans 天哪,谢谢!!!!是的,正是我需要的,并且从您的代码示例中学到了很多东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
  • 2020-10-06
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多