Search code examples
rcharacternumerical

How to change the axis values from numeric to character in R?


I'm having some issues trying to change the values of both axis.

All I wanna do it's just changing the values, those exact values that you can see in the picture (20, 0, -20,-40) to this characters: "20°N", "EQ","20°S and 40°S (The same goes with the x axis).

lat<-seq(-51.25,31.25,by=2.5)
lon<-seq(238.75,331.25,by=2.5)
data<-nc_open("aprecFeb2012.nc")
dataZG<-ncvar_get(data,"aprod")
dataz<-dataZG[96:133,16:49]

filled.contour(lon, lat, dataz,zlim =c(-500:500),
plot.axes={axis(1);axis(2);map('world2', add=TRUE);grid()})

Note: You can download the netcdf file that I'm using in this example here

Picture

P.D.: Please use the same function (filled.contour)

I'm just wanna says this really quick: You guys have been really helpful to me this past two years(the time since I've been using R), so helpful that this is my first question ever here in stackoverflow. Thank you so much

kind regards,

Freddy


Solution

  • The annotation for the x and y axis can be changed through the plot.axes parameter of filled.contour. See ?axis help file, which tells us at and labels can be defined for each axis side where 1=bottom (x axis), 2=left (y axis), 3=above, 4=right.

    at indicates points where tick-marks are to be drawn. labels are either a logical value specifying whether (numerical) annotations are to be used OR a character vector of labels to be placed in the tick-points.

    It is also helpful when asking questions in StackOverflow to indicate which packages have to be loaded in order to run your code. I included the libraries I had to install to answer this question :)

    library(ncdf4)
    library(graphics)
    library(maps)
    

    Set labels to desired character vector. The length of the labels vector should match the number of tick marks designated in at. I will only do the y axis where you have defined the character vectors, and leave the x axis annotation to you.

    filled.contour(lon, lat, dataz, zlim =c(-500:500),
               plot.axes={axis(1); axis(2, at=seq(-40,20,20), labels=c("20°S", "40°S","EQ", "20°N")); map('world2', add=TRUE);grid()})
    

    enter image description here

    Here is an example where labels take on a logical value, and we set different tick marks:

    filled.contour(lon, lat, dataz, zlim =c(-500:500),
               plot.axes={axis(1); axis(2, at=seq(-40,20,10), labels=TRUE); map('world2', add=TRUE);grid()})
    
    filled.contour(lon, lat, dataz, zlim =c(-500:500),
               plot.axes={axis(1); axis(2, at=seq(-40,20,10), labels=FALSE); map('world2', add=TRUE);grid()})