簡體   English   中英

R 上的 Base Plotting System 上未打印 X 軸標簽

[英]X-axis labels not printing on Base Plotting System On R

“R 版本 4.0.3 (2020-10-10)”

我有一些時間序列數據,試圖查看消費隨時間的變化。 這是一個代表。

set.seed(1)
date <-  seq(as.POSIXct('2010-01-01'),as.POSIXct('2010-04-10'),by=86400)
Consumption <- rnorm(99)


Data <- data.frame(date,Consumption)


plot(Data$Consumption~Data$date,type='l') # X-axis labels and ticks not printing
par(yaxt='n')
axis(side = 2,at=seq(-3,3,0.5),labels = seq(-3,3,0.5)) # This works on the first  plot on the y axis



plot(Data$date~Data$Consumption,type='l') # X-axis refusing to print despite assigning it.
par(xaxt='n')
axis(side = 1,at=seq(-3,3,0.5),labels = seq(-3,3,0.5)) # This works on the first  plot

初始plot()中輸出的圖形正是我想要的,除了它沒有任何 x 軸標簽。

我將 Base Plotting 用於作業而不是日常使用,並且通常會使用 ggplot。 我一直在試圖弄清楚為什么 x 軸沒有繪制。 最初我認為問題出在日期變量上,並嘗試使用lubridate::ymd()清理它。 但是,當我出於這個問題的目的開始制作上述 reprex 時,X 軸標簽和刻度很明顯沒有打印。 在第二個 plot 中,我將消費變量放在 x 軸上。 我驚訝地發現日期在 Y 軸上自己整齊地打印出來。

我究竟做錯了什么?

我可以很容易地看到兩個問題:

  1. 更改:Consumption <- rnorm(99) 到 Consumption <- rnorm(100) 以匹配日期列。

  2. 問題在於'par'。 當一個塊中有多個繪圖時,與 ggplot 不同,plot 無法正確處理。 刪除 par 並運行下面它應該工作

    set.seed(1)
    date <-  seq(as.POSIXct('2010-01-01'),as.POSIXct('2010-04-10'),by=86400)
    Consumption <- rnorm(100)
    Data <- data.frame(date,Consumption)
    plot(Data$Consumption~Data$date,type='l') 
    plot(Data$date~Data$Consumption,type='l') 

請注意,無論何時定義 par 以及在兩個不同的塊中運行每個 plot 時,標簽都會正確顯示。 你不會有任何問題。 但是當你 plot 兩個圖表都在一個塊中時,如果你有 par,你總會有問題。

當您想要更好地控制軸標簽和標題發生的情況時,您可以手動創建它們。 因此,首先生成一個沒有標題的 plot 和 label。然后,使用axis()mtext()手動創建它們。 在此過程中,您可以使用par(mar=...)增加 plot 底部的空間。 F.netuning 是用 arguments 完成的,比如lascex.axisline 最后,您將mar重置為其舊值。

您可以使用下面的代碼獲取更詳細的 X 軸標簽

### format to day (probably not the best way to do this) 
Data$date2 <-format(Data$date, "%d%b")
Data$date2 <- as.Date(Data$date2, format = "%d%b")

### increase room at bottom of the plot for X-axis title
### the labels will eat up space, if we do nothing it will be a mess
### set title with mtext later
par(mar = c(7,4,4,2))

### plot without X-axis labels (xaxt) and title (xlab)
### work with "at" and "labels" in axis-function
### rotate labels 90° (las) an reduce font (cex.axis)
### put title 5 lines below graph (line)
###
### Remark: the graph window has to be big enough
plot(Data$Consumption ~ Data$date, type= "l", xaxt = "n", xlab = NA) 
axis(side = 1, at = Data$date, labels =  Data$date2, las = 2, cex.axis=.75)
mtext(side = 1, text = "Date", line = 5)

這會產生下圖:

在此處輸入圖像描述

每第 7 個項目的替代刻度和標簽

per7 <- seq(1, 99, 7)
plot(Data$Consumption ~ Data$date, type= "l", xaxt = "n", xlab = NA) 
axis(side = 1, at = Data$date[per7], labels =  Data$date2[per7], las = 2, cex.axis=.75)
mtext(side = 1, text = "Date", line = 5)

### reset mar
par(mar = c(5,4,4,2))

它給出了以下圖片:

在此處輸入圖像描述

請讓我知道這是否是您想要的。

暫無
暫無

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

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