R Draw All Axis Labels (Prevent Some From Being Skipped)

后端 未结 6 1125
不思量自难忘°
不思量自难忘° 2020-12-09 10:20

When I manually add the following labels with (axis(1, at=1:27, labels=labs[0:27])):

> labs[0:27]
 [1] \"0\\n9.3%\"  \"1\\n7.6%\"  \"2\\n5.6%         


        
6条回答
  •  执念已碎
    2020-12-09 10:58

    Perhaps draw and label one tick at a time, by calling axis repeatedly using mapply...

    For example, consider the following data:

    x = runif(100)*20
    y = 10^(runif(100)*3)
    

    The formula for y might look a bit odd; it gives random numbers distributed across three orders of magnitude such that the data will be evenly distributed on a plot where the y axis is on a log scale. This will help demonstrate the utility of axTicks() by calculating nice tick locations for us on a logged axis.

    By default:

    plot(x, y, log = "y")
    

    returns:

    Notice that 100 and 1000 labels are missing.

    We can instead use:

    plot(x, y, log = "y", yaxt = "n")
    mapply(axis, side = 2, at = axTicks(2), labels = axTicks(2))
    

    which calls axis() once for each tick location returned by axTicks(), thus plotting one tick at a time. The result:

    What I like about this solution is that is uses only one line of code for drawing the axis, it prints exactly the default axis R would have made, except all ticks are labeled, and the labels don't go anywhere when the plot is resized:

    I can't say the axis is useful in the resized example, but it makes the point about axis labels being permanent!

    For the first (default) plot, note that R will recalculate tick locations when resizing.

    For the second (always labeled) plot, the number and location of tick marks are not recalculated when the image is resized. The axis ticks calculated by axTicks depend upon the size of the display window when the plot is first drawn.

    If you want want to force specific tick locations, try something like:

    plot(x, y, log = "y", yaxt = "n")
    mapply(axis, side = 2, at = c(1,10,100, 1000), labels = c("one", "ten", "hundred", "thousand"))
    

    which yields:

提交回复
热议问题