简体   繁体   中英

How to adjust the y-axis of bar plot in R using only the barplot function

Using this example:

 x<-mtcars;
 barplot(x$mpg);

you get a graph that is a lot of barplots from (0 - 30).

My question is how can you adjust it so that the y axis is (10-30) with a split at the bottom indicating that there was data below the cut off?

Specifically, I want to do this in base R program using only the barplot function and not functions from plotrix (unlike the suggests already provided). Is this possible?

This is not recommended. It is generally considered bad practice to chop off the bottoms of bars. However, if you look at ?barplot , it has a ylim argument which can be combined with xpd = FALSE (which turns on "clipping") to chop off the bottom of the bars.

barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE)

Also note that you should be careful here. I followed your question and used 0 and 30 as the y-bounds, but the maximum mpg is 33.9, so I also clipped the top of the 4 bars that have values > 30.

The only way I know of to make a "split" in an axis is using plotrix . So, based on

Specifically, I want to do this in base R program using only the barplot function and not functions from plotrix (unlike the suggests already provided). Is this possible?

the answer is "no, this is not possible" in the sense that I think you mean. plotrix certainly does it, and it uses base R functions, so you could do it however they do it, but then you might as well use plotrix .

You can plot on top of your barplot, perhaps a horizontal dashed line (like below) could help indicate that you're breaking the commonly accepted rules of what barplots should be:

abline(h = 10.2, col = "white", lwd = 2, lty = 2)

The resulting image is below:

在此处输入图片说明

Edit: You could use segments to spoof an axis break, something like this:

barplot(mtcars$mpg, ylim = c(10, 30), xpd = FALSE)
xbase = -1.5
xoff = 0.5
ybase = c(10.3, 10.7)
yoff = 0
segments(x0 = xbase - xoff, x1 = xbase + xoff,
         y0 = ybase-yoff, y1 = ybase + yoff, xpd = T, lwd = 2)
abline(h = mean(ybase), lwd = 2, lty = 2, col = "white")

As-is, this is pretty fragile, the xbase was adjusted by hand as it will depend on the range of your data. You could switch the barplot to xaxs = "i" and set xbase = 0 for more predictability, but why not just use plotrix which has already done all this work for you?!

ggplot In comments you said you don't like the look of ggplot . This is easily customized, eg:

library(ggplot2)
ggplot(x, aes(y = mpg, x = id)) +
    geom_bar(stat = "identity", color = "black", fill = "gray80", width = 0.8) +
    theme_classic()

在此处输入图片说明

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