Search code examples
rplotdensity-plot

How to force R plots y axis to start at y=0 and keep the color?


I am now trying to plot the Probability Density Functuion of some data, and I find the is some distance between y=0and x axis. I tried to set yaxs="i", but then the x axis will become grey. Is there any solution? Thanks. Here is an example

set.seed(100)
plot(density(rnorm(100)),xlab="",ylab="",main="")

enter image description here

plot(density(rnorm(100)),yaxs="i",xlab="",ylab="",main="")

As you can see, the color of the x axis will become grey. How to make it black? enter image description here


Solution

  • The reason you get the gray line is that you are calling plot.density when you pass an object class density to plot. plot.density has a zero.line argument which is set to TRUE and plots the gray line using abline(h = 0, lwd = 0.1, col = "gray") by default (see stat:::plot.density for code). You need to set zero.line to FALSE.

    plot(density(nums), yaxs="i", 
        xlab="", ylab="", main="",
        zero.line = FALSE)
    

    enter image description here

    You can control the upper ylim too if you want to give some more room at the top than yaxs = "i" would give otherwise. Of course, you still need zero.line = FALSE to not plot the gray zero line.

    plot(density(nums), yaxs="i",
        xlab="", ylab="", main="",
        zero.line = FALSE,
        ylim = c(0, 0.5)) # put whatever you want here instead 0.5
    

    An alternative solution would be to cover the gray line with another line:

    plot(density(nums), yaxs="i",
        xlab="", ylab="", main="")
    abline(h = 0)