gpt4 book ai didi

r - 如何调整在ggplot2中绘制轴的程度?

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

这个问题在这里已经有了答案:





how to prevent axes from intersecting in ggplot2

(1 个回答)


去年关闭。




我对 ggplot2 比较陌生,已经在 R 中使用了多年的基本图形。我一直喜欢基本图形的一件事是轴中的额外填充,这样两个轴就不会在原点接触。这是基本图形中的一个简单示例:

png(file="base.png")
plot(x,y, bty="n")
dev.off()

这使得:

base graphics

然而,当我在 ggplot2 中做类似的事情时
require(ggplot2)
x <- y <- 1:10
png(file="qplot.png")
qplot(x, y) + theme_classic()
dev.off()

我得到:

qplot graphics

如何调整绘制轴的程度?例如对于 y 轴,我希望它停止在 10.0,而不是继续到大约 10.5?

更新:感谢您的评论。我现在有我想要的;这是一个片段,仅将轴绘制到每个轴上的最小/最大刻度。
o = qplot(x, y) + theme_classic() +
theme(axis.line=element_blank())
oo = ggplot_build(o)
xrange = range(oo$panel$ranges[[1]]$x.major_source)
yrange = range(oo$panel$ranges[[1]]$y.major_source)
o = o + geom_segment(aes(x=xrange[1], xend=xrange[2], y=-Inf, yend=-Inf)) +
geom_segment(aes(y=yrange[1], yend=yrange[2], x=-Inf, xend=-Inf))
plot(o)

better axes

最佳答案

带参数 expand=功能 scale_x_continuous()scale_y_continuous()您可以获得以特定值开始和结束的轴。但是,如果您不提供这些值,那么它将看起来像被削减了点。

qplot(x, y) + theme_classic()+
scale_x_continuous(expand=c(0,0))

enter image description here

要获得基本图的外观,一种解决方法是使用 theme() 删除轴线。然后用 geom_segment() 代替它们添加从值 2 到 10 的行(例如) .
qplot(x, y) + theme_classic()+
scale_x_continuous(breaks=seq(2,10,2))+
scale_y_continuous(breaks=seq(2,10,2))+
geom_segment(aes(x=2,xend=10,y=-Inf,yend=-Inf))+
geom_segment(aes(y=2,yend=10,x=-Inf,xend=-Inf))+
theme(axis.line=element_blank())

enter image description here

关于r - 如何调整在ggplot2中绘制轴的程度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25327694/

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