简体   繁体   中英

Hiding tick marks and tick labels of minimum and maximum limits of axes for base R plots

Suppose I make a barplot and a scatterplot using the following lines of code:

x <- c(1, 2, 3)
xlabs <- c("A", "B", "C")
y <- c(4, 5, 6)

barplot(x,
        xlab = "X",
        names.arg = xlabs,
        ylim = c(0, 3),
        ylab = "Y")

plot(x, y,
        xlim = c(1, 3),
        xlab = "X",
        ylim = c(4, 6),
        ylab = "Y")

How can the axes tick marks and tick labels for the minimum and maximum limits only be hidden? Here is what I intend to accomplish:

在此处输入图片说明

在此处输入图片说明

There are a couple of options. First, you generally want to drop the default axis labels using xaxt='n' or yaxt='n' . Next, you could manually specify the locations of the tick marks in axis() or use the pretty() function with dropping the first and last values (used head and tail in example) to get some nice tick mark locations. It might require some manual fine tuning.

x <- c(1, 2, 3)
xlabs <- c("A", "B", "C")
y <- c(4, 5, 6)

barplot(x,
        xlab = "X",
        names.arg = xlabs,
        ylim = c(0, 3),
        ylab = "Y",
        yaxt='n' # drops the y axis and tick marks
        )
# draw a vertical line that will cover the whole vertical axis, if desired
abline(v=par('usr')[1],lwd=2)
# pretty will give nice tickmark locations, and head and tail drop first and last
# add the 0 to x vector because barplot starts at 0
axis(side=2,tail(pretty(c(0,x)),-1)) 

plot(x, y,
     xlim = c(1, 3),
     xlab = "X",
     ylim = c(4, 6),
     ylab = "Y",
     xaxt='n', # no default x axis with ticks
     yaxt='n' # no default y axis with ticks
     )
# add tickmark and axis locations manually for each axis
# using the pretty function for where the tick marks normally would be, then head and tail to drop first and last
axis(side=1,tail(head(pretty(c(x)),-1),-1)) 
axis(side=2,tail(head(pretty(c(y)),-1),-1))

散点图

条形图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM