修复 r 中绘图的 x 轴和网格线

Fixing the x axis and the gridline of a plot in r

我正在尝试使用 R 在图表上可视化数据。

下面的代码运行完美,但网格线似乎丢失了(见下图)。

with(res_final, plot(position_aa, mean_res, main="Hydrophobicity",
               xlab="Amino acid position",
               ylab="Eisenberg scale"))
with(res_final, points(position_aa, mean_res, pch=10, cex=0.5))
.col <- rgb(0, 0, 0, .25)  ## alpha .25 for transparency
abline(h=axTicks(3), lty=3, col=.col)
abline(v=seq(-10:14), lty=3, col=.col) 

  1. 我有从-10到14的位置。我怎样才能使x轴的每个位置都单独标记?

  2. 如何将网格线添加到下图中,以便从 x 轴的每个位置都可见?

您尚未提供任何数据,但以下是一个合理的近似值:

set.seed(69)

res_final <- data.frame(position_aa = seq(-10, 14, 1),
                        mean_res = c(runif(10, -0.5, 0.25), 
                                     runif(4, 0.5, 1.25),
                                     runif(11, -0.5, 0.25)))

您的代码的主要问题是您对 seq 的使用没有按照您的想法进行。获取-10 到 14 之间的序列的方法是 seq(-10, 14, 1)seq(-10, 14)。此更改将使您的网格线按预期显示。

对于第二个问题,您可以添加一个 axis 调用,使用 pos = 1at 参数来指定轴上的中断。您需要确保绘图区域足够宽(或轴文本足够小),以免某些数字被抑制。

with(res_final, plot(position_aa, mean_res, main = "Hydrophobicity",
               xlab = "Amino acid position",
               ylab = "Eisenberg scale"))
axis(pos = 1,  at = seq(-10, 14, 1))
with(res_final, points(position_aa, mean_res, pch = 10, cex = 0.5))
.col <- rgb(0, 0, 0, .25)
abline(h = axTicks(3), lty = 3, col = .col)
abline(v = seq(-10, 14, 1), lty = 3, col = .col) 

为了完整起见,ggplot 中的等价物为:

library(ggplot2)

ggplot(res_final, aes(position_aa, mean_res)) +
  geom_point(shape = 21, size = 5, fill = "white") +
  geom_point(shape = 21, size = 2, fill = "black") +
  scale_x_continuous(breaks = seq(-10, 14)) +
  theme_bw() +
  theme(panel.grid.minor = element_blank(),
        text = element_text(size = 15),
        plot.title.position = "plot",
        plot.title = element_text(hjust = 0.5)) +
  labs(title = "Hydrophobicity",
       x = "Amino acid position",
       y = "Eisenberg scale")