【问题标题】:Formatting X axis label in R for a specific condition针对特定条件在 R 中格式化 X 轴标签
【发布时间】:2015-03-13 15:05:56
【问题描述】:

对于以下示例代码:

y <- c(23, 34, 11, 9.6, 26, 31, 38, 38, 30, 36, 31)
days <- seq(as.Date("2015-2-25"), by="day", length=11)
n <- length(y)
x <- 1:n
plot(x, y, type='n', xlab="Days", ylab="Y", xaxt='n')
axis(1, at=seq(1,11) ,labels=format(days, "%d"), las=1)
lines(y)

我有以下图表:

我想要的是当月份发生变化时,我希望能够在 x 轴上的日期下方添加月份名称。所以在这个例子中,当它变成 01 时,它应该显示 01 Mar(三月在单独的一行)

【问题讨论】:

    标签: r plot label axis


    【解决方案1】:

    如果您执行以下操作,可能会发生这种情况:

    您的数据加上月份向量:

    y <- c(23, 34, 11, 9.6, 26, 31, 38, 38, 30, 36, 31)
    days <- seq(as.Date("2015-2-25"), by="day", length=11)
    
    #my addition
    #contains the name of the month for where day == '01' else is blank
    months <- ifelse(format(days, '%d')=='01',  months(days) , '') 
    
    n <- length(y)
    x <- 1:n
    

    解决方案:

    plot(x, y, type='n', xlab="Days", ylab="Y", xaxt='n')
    axis(1, at=seq(1,11) ,labels=format(days, "%d"), las=1)
    lines(y)
    

    到这里为止只是您的代码。现在您需要添加一个新轴,将轴颜色设置为白色并绘制上面创建的月份向量:

    par(new=T)           #new plot
    par(mar=c(4,4,4,2))  #set the margins. Original are 5,4,4,2.
    #I only changed the bottom margin i.e. the first number from 5 to 4
    
    #plot the new axis as blank (colour = 'white')
    axis(1, at=seq(1,11) ,labels=months, las=1, col='white')
    

    结果看起来像您要求的那样:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多