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 轴标签和刻度很明显没有打印。在第二个图中,我将消费变量放在 x 轴上。我惊讶地发现日期在 Y 轴上自己整齐地打印出来。

我做错了什么?

有两个问题我很容易看出:

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

  2. 问题出在 'par'。当一个块中有多个绘图时,与 ggplot 不同,绘图无法正确处理。删除 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 以及 运行 将每个绘图分成两个不同的块,标签都会正确显示。你不会有任何问题。但是当你将两个图表绘制在一个块中时,如果你有 par.

如果您想要更好地控制轴标签和标题发生的情况,您可以手动创建它们。所以,首先制作一个没有标题和标签的图。然后,使用 axis()mtext() 手动创建它们。在此过程中,您可以使用 par(mar=...) 增加地块底部的空间。微调是通过 lascex.axisline 等参数完成的。最后,您将 mar 重置为其旧值。

您可以使用下面的代码获取更详细的 X-axis 标签

### 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))

给出了下图:

请告诉我这是否是您想要的。