【问题标题】:R: Character instead of level # on x axis when plotting?R:绘图时x轴上的字符而不是级别#?
【发布时间】:2017-08-10 16:23:43
【问题描述】:

我需要帮助在 x 轴上绘制月份名称,而不是月份分配的级别。我正在处理“水年”,因此将 10 月分配为 1 级,并以 9 月结束为 12 级。我相信这很容易,我只是不经常使用因子。谢谢!

研究完成: Plot a character vector against a numeric vector in R

R plotting, date on x axis

这是我的数据的简化示例

    Months<-c("Jan"=4,"Feb"=5,"Mar"=6,"Apr"=7,"May"=8,"Jun"=9,"Jul"=10,
    "Aug"=11,"Sep"=12,"Oct"=1,"Nov"=2,"Dec"=3)

    Data<-c(1,2,3,4,5,6,7,8,9,10,11,12)

    df<-data.frame(Months,Data)

  >df
      Months Data
  Jan      4    1
  Feb      5    2
  Mar      6    3
  Apr      7    4
  May      8    5
  Jun      9    6
  Jul     10    7
  Aug     11    8
  Sep     12    9
  Oct      1   10
  Nov      2   11
  Dec      3   12

    plot(Data~factor(Months), df,las=2)

这会将数据以正确的月份放在正确的位置,只是标签错误。

【问题讨论】:

    标签: r plot factors


    【解决方案1】:

    我们可以在plot 中使用xaxt = "n",然后使用axis 更改xaxis 刻度标签

    plot(Data ~ Months, transform(df, Months = match(row.names(df), 
                           month.abb)), las = 2, xaxt = "n", type = "b", col = "blue")
    axis(1, at = seq_len(nrow(df)), row.names(df))
    

    【讨论】:

      【解决方案2】:

      使用plot xaxt = "n" 的参数,然后使用axis 函数。

      plot(Data ~ factor(Months), df, las=2, xaxt = "n")
      axis(1, at = factor(df$Months), label = row.names(df))
      

      【讨论】:

      • 这个轴函数效果更好,因为它保持了正确的月份顺序。
      猜你喜欢
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-08
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      相关资源
      最近更新 更多