ggplot绘图区域上下的线条

3

我想在使用ggplot2创建的图形上方和下方添加一条线(x标签和轴下方的底线)。到目前为止,我已经在图形周围添加了一个矩形,但我不想要两侧的线。

x <- 1:10
y <- rnorm(10,mean = x)
df <- data.frame(x,y)
library(ggplot2)
ggplot(data = df, mapping = aes(x,y)) + geom_point() +
  theme(plot.background = element_rect(size = 1, color = 'blue'))

我希望你们有解决办法。
3个回答

1
这句话的意思是:"类似于this这样的东西能起作用吗?"。
x <- 1:10
y <- rnorm(10,mean = x)
df <- data.frame(x,y)
ggplot(data = df, mapping = aes(x,y)) + geom_point() +
    annotate(geom = 'segment', 
             y = Inf, 
             yend = Inf, 
             x = -Inf, 
             xend = Inf, 
             size = 2) +
    theme(axis.line.x = element_line(size = 1))

enter image description here


很遗憾不行,因为我需要底部线在坐标轴和 X 标签下面,但还是谢谢! - Markus

0

这不是一个完美的解决方案,但是它可以工作。您必须在绘图区域外绘制巨大的“-”(size = 1000)。这个解决方案并不完美,因为您必须手动调整“-”在y轴上的位置。

df <- data.frame(x = 1:10, y = 1:10)
library(ggplot2)
ggplot(df, aes(x, y)) + 
    geom_point() +
    # Y position adjusted manually
    geom_text(aes(5, 2.9, label = "-"), color = "blue", size = 1000)  +
    # Y position adjusted manually
    geom_text(aes(5, 21.2, label = "-"), color = "blue", size = 1000)  +
    # Plot outside plot area
    coord_cartesian(ylim = c(0, 10), clip = "off")

enter image description here


0

我对解决方案并不完全满意,因为我没有完全掌握:

  • 如何更改线条的大小
  • 使用patchwork::wrap_plots()时,为什么它们与顶部和底部的对齐不完美
  • 为什么使用ggpubr::ggarrange()cowplot::plot_grid()时它不显示顶部线

但基于this code,我建议以下解决方案:

library(ggplot2)
df <- data.frame(x = 1:5, y = 1:5)
p <- ggplot(data = df) + aes(x, y) + geom_point() 

top_line <- grid::grobTree(grid::linesGrob(x = grid::unit(c(0, 1), "npc"), y = grid::unit(1, "npc")))
bot_line <- grid::grobTree(grid::linesGrob(x = grid::unit(c(0, 1), "npc"), y = grid::unit(0, "npc")))

patchwork::wrap_plots(top_line, p, bot_line,
                      ncol = 1, nrow = 3,
                      heights = c(0, 1, 0))

ggpubr::ggarrange(top_line, p, bot_line,
                  ncol = 1, nrow = 3,
                  heights = c(0, 1, 0))

cowplot::plot_grid(top_line, p, bot_line,
                   ncol = 1, nrow = 3,
                   rel_heights = c(0, 1, 0))

使用 reprex v2.0.2 工具于2022年8月25日创建


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接