R -调整y轴的值标签

axr492tv  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(198)

我正在为内置的数据集汽车在R中创建一个直方图。我想调整y轴,使其显示为c(0,“",0.04,“",0.08)。但是,我似乎做不到。
我尝试将新的标签值保存为列表,然后在text()函数中调用该列表...此外,我还尝试了以下方法:

data(cars)

    hist(cars$speed,
      main = "",
      breaks = 11,
      xlab = "Speed",
      ylab = "Density",
      yaxt = "n",  
      freq = FALSE)
    axis(side=2,
      at = 1:5,
      labels = c(0, "", 0.04, "", 0.08), 
      las = 2,
      mgp = c(3, 2, 1))

在我看来,这应该可以工作,但我没有从axis()函数中获得输出。我做错了什么?
PS:除此之外,当我接受自动生成的y轴时,通过删除yaxt=“n”,会发生另一个错误。y轴值标签打印在y轴标签“密度”的顶部。这不应该是这样的,因为MGP[1]…你犯了什么错?

qnyhuwrf

qnyhuwrf1#

看不到y轴的原因是yaxt = "n"(关闭y轴)。以下是两种可能的解决方案:

base R:

hist(cars$speed,
     main = "",
     breaks = 11,
     xlab = "Speed",
     ylab = "Density",
     yaxt = "n",  
     freq = FALSE)

text(x = par("usr")[1] - 0.01 * diff(par("usr")[1:2]), 
     y = seq(0, 0.08, by = 0.04),
     labels = c(0, "", 0.04, "", 0.08), 
     xpd = TRUE, 
     adj = 1, 
     col = "black", 
     cex = 1)

axis(side = 2, 
     at = seq(0, 0.08, by = 0.04), 
     labels = FALSE, 
     lwd = 1, 
     col = "black", 
     tck = -0.02, 
     lty = 1, 
     las = 1, 
     mgp = c(3, 2, 0))

ggplot

library(ggplot2)
data(cars)

ggplot(cars, aes(x = speed)) +
  geom_histogram(aes(y = ..density..), bins = 11, color = "black", fill = "gray", alpha = 0.5) +
  scale_y_continuous(breaks = c(0, 0.04, 0.08), labels = c(0, 0.04, 0.08)) +
  labs(x = "Speed", y = "Density") +
  theme_minimal()

相关问题