R: Character instead of level # on x axis when plo

2019-08-18 03:45发布

I need help plotting month names on the x axis, instead of the level the months are assigned. I am working with a "water year", so October is assigned to be level 1, and ending with September being level 12. I'm sure this is easy, I just don't often work with factors. Thanks!

Research Done: Plot a character vector against a numeric vector in R

R plotting, date on x axis

Here is a simplified example of my data

    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)

This puts the data in the correct place with the correct month, just the wrong labels.

标签: r plot factors
2条回答
趁早两清
2楼-- · 2019-08-18 04:24

We can use xaxt = "n" in plot and then with axis change the xaxis tick labels

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))
查看更多
混吃等死
3楼-- · 2019-08-18 04:29

Use argument to plot xaxt = "n" and then function axis.

plot(Data ~ factor(Months), df, las=2, xaxt = "n")
axis(1, at = factor(df$Months), label = row.names(df))
查看更多
登录 后发表回答