Yang Yang
Yang Yang

Reputation: 902

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

Upvotes: 2

Views: 3603

Answers (2)

shayaa
shayaa

Reputation: 2797

If you specify the ylim, it should work.

d <- density(rnorm(100))
plot(d, xlab = "", ylab = "", ylim = c(0,max(d$y)), yaxs = "i")

you could also specify

par(col.axis = "black")

Looks as follows, i.e., starting at 0 and keeping the color.

d <- density(rnorm(100))
plot(d, xlab = "", ylab = "", ylim = c(0,max(d$y)+.05), yaxs = "i",
     col.axis = "black")

enter image description here

Upvotes: 0

Jota
Jota

Reputation: 17621

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)

Upvotes: 3

Related Questions