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

HCA*_*CAI 11 r ggplot2 plotly

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

在此输入图像描述

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
Run Code Online (Sandbox Code Playgroud)

Max*_*ers 10

让我们从这里使用一个简单的可重复的例子.

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我们可以按照MLavoie的建议移动调整边距,但我们的轴图例也会移动.

gp %>% layout(margin = list(l = 75))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

轴图例实际上不是图例而是注释,所以让我们先移动它:

# 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>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


小智 5

从Github上找到一个答案,优雅地解决了这个问题。

layout_ggplotly <- function(gg, x = -0.02, y = -0.08){
  # The 1 and 2 goes into the list that contains the options for the x and y axis labels respectively
  gg[['x']][['layout']][['annotations']][[1]][['y']] <- x
  gg[['x']][['layout']][['annotations']][[2]][['x']] <- y
  gg
}
gp %>% layout_ggplotly
Run Code Online (Sandbox Code Playgroud)