如何强制 R plots y 轴从 y=0 开始并保持颜色?

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

我现在正在尝试绘制一些数据的概率密度函数,我发现 y=0 和 x 轴之间有一些距离。我试着设置yaxs="i",但是x轴会变成灰色。有什么解决办法吗?谢谢。这是一个例子

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

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

如你所见,x轴的颜色会变成灰色。怎么让它变黑?

如果您指定 ylim,它应该可以工作。

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

你也可以指定

par(col.axis = "black")

看起来如下,即从 0 开始并保持颜色。

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

你得到灰线的原因是当你传递一个对象class densityplot时你正在调用plot.densityplot.density 有一个设置为 TRUE 的 zero.line 参数,默认情况下使用 abline(h = 0, lwd = 0.1, col = "gray") 绘制灰线(请参阅 stat:::plot.density 了解代码)。您需要将 zero.line 设置为 FALSE。

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

如果您想在顶部留出比 yaxs = "i" 更多的空间,您也可以控制上层 ylim。当然,你还需要zero.line = FALSE不画灰色零线

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

另一种解决方案是用另一条线覆盖灰色线:

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