簡體   English   中英

X軸標簽在R圖中成束在一起

[英]X-axis labels bunched together in R plot

我正在使用R繪制值,並嘗試用我自己的x軸標簽替換如下:

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

最小值(年)= 1969,最大值(年)= 2016。

繪圖本身看起來不錯,但x軸刻度標簽卻不是:

使用不正確的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"]]

一個問題是,您將日期factor視為與數字相關。 在內部,一個factor只是一個integer ,這意味着它們按順序繪制很方便,但不能反映實際$date之間的有效距離。

而是將它們轉換為實際的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對象的打印格式,而又可以獲取完整Date對象的值/位置。

簡單的按日圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM