r - 切断散点图网格线,但不完全在轴限制处标记

标签 r ggplot2

我有一些 x 值在 0 到 100 范围内的数据,如下所示:

library(ggplot2)
set.seed(42)
df <- data.frame(x=c(rep(100, 20), runif(100, min=0, max=100)),
                 y=rnorm(120, mean=4, sd=2))

由以下代码生成的简单散点图:
ggplot(df, aes(x=x, y=y)) +
    geom_point(size=5) +
    theme(panel.grid.major=element_line(color='black'),
          panel.grid.minor=element_line(color='black'),
          panel.background=element_rect(fill='white'))

看起来像这样:
Ordinary scatterplot with a healthy x-margin.

但是为了强调 0 到 100 范围之外的 x 值是没有意义的,我想在 x=0 和 x=100 处精确裁剪 x 轴和水平网格线。我了解到正确的方法是使用 expand , 通过添加 scale_x_continuous(limits=c(0, 100), expand=c(0, 0))到我的 ggplot目的。结果:Scatterplot with no margins and with clipped markers and x-labels

这会缩短网格线,但也会裁剪左右边距处的散点图标记,以及 x 轴上的 100 标签。我可以在边距之前只切断 x 轴和网格线,但渲染标记和轴标签就好像边距仍然存在一样吗?

最佳答案

您可以使用 geom_segment 控制网格线的范围创建网格线。例如:

library(ggplot2)
library(scales)

yr = pretty(df$y)
xr = pretty(df$x)

ggplot() +
  geom_segment(aes(y=rep(min(yr), length(xr)), yend=rep(max(yr), length(xr)),
                   x=xr, xend=xr), colour="grey70") +
  geom_segment(aes(x=rep(min(xr), length(yr)), xend=rep(max(xr), length(yr)),
                   y=yr, yend=yr), colour="grey70") +
  geom_point(data=df, aes(x,y), size=5) + 
  scale_y_continuous(breaks=yr, expand=c(0,0.02*diff(range(df$y)))) +
  scale_x_continuous(breaks=xr, expand=c(0,0.02*diff(range(df$x)))) +
  theme_classic() +
  theme(axis.line=element_blank()) +
  labs(x="x", y="y")

enter image description here

关于r - 切断散点图网格线,但不完全在轴限制处标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46126233/

相关文章:

r - 如何删除ggplot geom_bar图例的横杆?

r - 绘图的两个方面的两个单独的 y 轴标题,同时使用 ggplot2 保留方面顶部 strip 标签

使用 ggcorrplot2 : "x-axis" labels get cropped 的 R 相关图

RStudio 本地 + R 云

r - read.table() 和 read.csv() 中的 skipNul = TRUE 有什么作用(除了跳过/忽略嵌入的空值)?

r - 如何在 R 中使用 stripchart() ?

r - 嵌套列表赋值 R

r - str_extract 仅捕获重复出现的关键字的一个实例

r - 在ggplot2中轻松地将 '(all)' facet添加到facet_wrap?

r - 是否可以在 ggplot2 中创建具有不同颜色的平滑、大的 geom_line()?