[英]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 轴上自己整齐地打印出来。
我究竟做错了什么?
我可以很容易地看到两个问题:
更改:Consumption <- rnorm(99) 到 Consumption <- rnorm(100) 以匹配日期列。
问题在于'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 完成的,比如las
、 cex.axis
和line
。 最后,您将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.