gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:48:57 25 4
gpt4 key购买 nike

我有一些 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com