gpt4 book ai didi

r - 在 R 中使用 ggplot 时,如何删除绘图区域周围的边距?

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

我正在尝试生成一些分形,并且对 R 中 ggplot 的边距有疑问。我正在使用以下代码生成分形。

library(ggplot2)
library(grid)

max_iter=25
cl=colours()
step=seq(-2,0.8,by=0.005)
points=array(0,dim=c(length(step)^2,3))
t=0

for(a in step) {
for(b in step+0.6) {
x=0;y=0;n=0;dist=0
while(n<max_iter & dist<4) {
n=n+1
newx=a+x^2-y^2
newy=b+2*x*y
dist=newx^2+newy^2
x=newx;y=newy
}

if(dist<4) {
color=24 # black
} else {
color=n*floor(length(cl)/max_iter)
}
t=t+1
points[t,]=c(a,b,color)
}
}

df=as.data.frame(points)

ggplot(data=df, aes(V1, V2, color=cl[V3]))+
geom_point() +
theme(panel.background=element_blank(),
panel.grid.major=element_blank(),
panel.grid.minor=element_blank(),
panel.margin = unit(c(0, 0, 0, 0), "cm"),
axis.ticks=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_blank(),
axis.title.x=element_blank(),
axis.title.y=element_blank(),
plot.background = element_rect(fill = "transparent",colour = NA),
plot.margin = unit(c(0, 0, 0, 0), "cm"),
legend.position = 'none')

last_plot() + scale_colour_manual(values=sort(c("#00000000", rainbow(35)), decreasing=FALSE))

ggsave('mandelbrot.png');
print('Image Saved.')

我正在寻找删除绘图区域周围边距的想法。我尝试了很多技巧,例如在“par”、xaxes/yaxes、last_plot() + labs(x=NULL, y=NULL) 等中设置参数,但似乎没有任何效果。

有没有人有想法从情节中删除这个棘手的边缘?我还考虑设置一个透明的背景,但我必须剪掉边距——这是我想避免的一步。

enter image description here

最佳答案

您也可以使用 theme_nothing()来自 cowplot包裹:

require(cowplot)
qplot(1:10, (1:10)^2, geom='line') + theme_nothing() +
scale_x_continuous(expand=c(0,0)) +
scale_y_continuous(expand=c(0,0)) +
labs(x = NULL, y = NULL)

不幸的是,您仍然需要添加 labs(x = NULL, y = NULL) ,因为 ggplot2 的主题机制无法完全移除轴。而你需要设置 expand=c(0,0)在比例参数中,以确保比例不会超出您的数据范围。

结果:

enter image description here

关于r - 在 R 中使用 ggplot 时,如何删除绘图区域周围的边距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31254533/

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