问题
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.
回答1:
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))
回答2:
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))
来源:https://stackoverflow.com/questions/45618931/r-character-instead-of-level-on-x-axis-when-plotting