gpt4 book ai didi

R:ggplot 和 plotly 轴边距不会改变

转载 作者:行者123 更新时间:2023-12-04 02:09:17 25 4
gpt4 key购买 nike

我在使用 ggplotly 阻止 y 轴文本与刻度重叠时遇到问题附近ggplot .我怎样才能解决这个问题?我试过以下代码:

enter image description here

set.seed(395)
df1<- data.frame(CO2= c(cumsum(rnorm(1*36)), cumsum(rnorm(1*36))),
Group= rep(c("A","B"), each=36),
Segment=rep(seq(1,12),each=36))

plot<-ggplot(df1, aes(CO2, fill = Group)) +
geom_density(alpha = 0.8)+
facet_wrap(~ Segment)+
theme_bw()+
labs(x="CO2", y="density")
#Shouldn't the following work?
pb <- plotly_build(plot)
pb$layout$margin$l <- 200
pb$layout$margin$b <- 100
pb

最佳答案

让我们使用来自 here 的一个简单的可重现示例.

library(gapminder)
library(plotly)
p <- ggplot(gapminder, aes(x=gdpPercap, y=lifeExp)) + geom_point() + scale_x_log10()
p <- p + aes(color=continent) + facet_wrap(~year)
gp <- ggplotly(p)

enter image description here

我们可以移动调整 margins正如 MLavoie 所建议的那样,但我们的轴图例也会移动。
gp %>% layout(margin = list(l = 75))

enter image description here

轴标签实际上不是标签而是注释,所以我们先移动它。可以查询图中标注的结构 gp :
# find the annotation you want to move
str(gp[['x']][['layout']][['annotations']])

List of 15
$ :List of 13
..$ text : chr "gdpPercap"
..$ x : num 0.5
..$ y : num -0.0294
..$ showarrow : logi FALSE
..$ ax : num 0
..$ ay : num 0
..$ font :List of 3
.. ..$ color : chr "rgba(0,0,0,1)"
.. ..$ family: chr ""
.. ..$ size : num 14.6
..$ xref : chr "paper"
..$ yref : chr "paper"
..$ textangle : num 0
..$ xanchor : chr "center"
..$ yanchor : chr "top"
..$ annotationType: chr "axis"
$ :List of 13
..$ text : chr "lifeExp"
..$ x : num -0.0346
..$ y : num 0.5
.... <truncated>

好的,所以注释存储在 15 个列表中; “lifeExp”是 第二个 ( [[2]] ) 此列表的元素。在这种情况下,“x”( [['x']] )和“y”值分别控制左右/上下移动。
# Check current x-location of x-axis label
gp[['x']][['layout']][['annotations']][[2]][['x']]
[1] -0.03459532

# Move the label further to the left
gp[['x']][['layout']][['annotations']][[2]][['x']] <- -0.1
gp %>% layout(margin = list(l = 75))

enter image description here

关于R:ggplot 和 plotly 轴边距不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763280/

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