【问题标题】:How to show only a subset of labels on x-axis?如何在 x 轴上仅显示标签的子集?
【发布时间】:2020-11-20 16:18:04
【问题描述】:

我在 R 中绘制图(不是 ggplot,只是基本的 R),我使用以下代码设置自定义 x 轴值:

plot(my_vector, level=1, labels = F, col = c("red", "green", "blue", "orange", "black"), xaxt='n')

axis(1, at=1:length(date_tot), labels=format(as.Date(date_tot, "%Y-%m-%d"), "%d-%m"), las=2, tick=F)

legend(x="topright", col=c("red", "green", "blue", "orange", "black"), legend=my_names, lwd=2, bty='n')

输出如下:

由于 x 轴的格式不正确,我想:

  1. 仅显示日期的子集(例如,每三个日期一个)
  2. 将 x 轴的标签移出绘图(稍微向下)

我该怎么做?

【问题讨论】:

  • 您明确地使用1:length(date_tot) 执行此操作。相反,使用它创建一个向量,然后vec[seq_along(vec) %% 3 == 0] 将为您提供每三个元素。标签也一样。 (我会用你的真实情节来演示,但我们没有你的数据。)
  • 也许是vec <- seq_along(date_tot); ind <- ind[ ind %% 3 == 0 ];,现在只需将[ind] 添加到您的每个at=labels= 向量中。
  • 是的,你是对的。有用。您对第二个问题有什么建议吗?
  • 您保留分类 x 轴是否有原因?它们代表日期的事实并没有什么不同,如果您的任何间隔都不是 4 天,那么该图将不会显示实际日期差异的成比例跨度。 (此外,它可能会产生更直观和 R 惯用的轴刻度位置。)
  • 不,不强制使用分类标签

标签: r plot graphics time-series


【解决方案1】:

示例:

y <- mtcars$disp
plot(y, pch = 16, xaxt = "n")
axis(1, seq_along(y), las = 2)

ind <- seq_along(y)
ind <- ind[ ind %% 3 == 0 ]
ind
#  [1]  3  6  9 12 15 18 21 24 27 30
plot(y, pch = 16, xaxt = "n")
axis(1, at = seq_along(y)[ind])

关于你的第二个问题,我无法重现它......也许你已经以影响利润等的方式调整了 par。 (也许关闭并重新打开您的图形设备...dev.off()?)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2019-01-28
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多