How to specify the actual x axis values to plot as x axis ticks in R

后端 未结 4 1895
太阳男子
太阳男子 2020-11-28 03:00

I am creating a plot in R and I dont like the x axis values being plotted by R.

For example:

x <- seq(10,200,10)
y <- runif(x)

plot(x,y)


        
相关标签:
4条回答
  • 2020-11-28 03:24

    You'll find the answer to your question in the help page for ?axis.

    Here is one of the help page examples, modified with your data:

    Option 1: use xaxp to define the axis labels

    plot(x,y, xaxt="n")
    axis(1, xaxp=c(10, 200, 19), las=2)
    

    Option 2: Use at and seq() to define the labels:

    plot(x,y, xaxt="n")
    axis(1, at = seq(10, 200, by = 10), las=2)
    

    Both these options yield the same graphic:

    enter image description here


    PS. Since you have a large number of labels, you'll have to use additional arguments to get the text to fit in the plot. I use las to rotate the labels.

    0 讨论(0)
  • 2020-11-28 03:26

    Hope this coding will helps you :)

    plot(x,y,xaxt = 'n')
    
    axis(side=1,at=c(1,20,30,50),labels=c("1975","1980","1985","1990"))
    
    0 讨论(0)
  • 2020-11-28 03:37

    In case of plotting time series, the command ts.plot requires a different argument than xaxt="n"

    require(graphics)
    ts.plot(ldeaths, mdeaths, xlab="year", ylab="deaths", lty=c(1:2), gpars=list(xaxt="n"))
    axis(1, at = seq(1974, 1980, by = 2))
    
    0 讨论(0)
  • 2020-11-28 03:40

    Take a closer look at the ?axis documentation. If you look at the description of the labels argument, you'll see that it is:

    "a logical value specifying whether (numerical) annotations are 
    to be made at the tickmarks,"
    

    So, just change it to true, and you'll get your tick labels.

    x <- seq(10,200,10)
    y <- runif(x)
    plot(x,y,xaxt='n')
    axis(side = 1, at = x,labels = T)
    # Since TRUE is the default for labels, you can just use axis(side=1,at=x)
    

    Be careful that if you don't stretch your window width, then R might not be able to write all your labels in. Play with the window width and you'll see what I mean.


    It's too bad that you had such trouble finding documentation! What were your search terms? Try typing r axis into Google, and the first link you will get is that Quick R page that I mentioned earlier. Scroll down to "Axes", and you'll get a very nice little guide on how to do it. You should probably check there first for any plotting questions, it will be faster than waiting for a SO reply.

    0 讨论(0)
提交回复
热议问题