轴标题使用rmarkdown + plotly与轴刻度重叠

时间:2019-12-19 15:35:48

标签: r ggplot2 plotly

在rmarkdown中使用plotly时,轴标题与轴刻度重叠。我已经尝试过Plot margins in RMarkdown/knitrR: ggplot and plotly axis margin won't changeY Axis - Margin Size。没有成功显示我的代码:

只有ggplot可以正常工作:

    ---
    title: |
      SLIDES
   author: |
      ME   
   date: |
      `r format(Sys.time(), '%d %B, %Y')`

   output: slidy_presentation
   runtime: knitr
   ---
```{r my.chunk, echo=FALSE, fig.width = 18, fig.height = 9, results='asis', message=FALSE}
   require(ggplot2)
   require(plotly)
   d<-data.frame(Year=rep(c(2020:2024),6),Group=rep(c('A','B','C'),each=10),Item=rep(c('w','v'),each=5),
                 Value=round(runif(30,100,500),0))
   g<-ggplot(d, aes(Year,Value,fill=Item ))+ 
     geom_bar( position = "stack", stat = "summary", fun.y = "sum",na.rm=T)+
     scale_y_continuous(labels = scales::comma) +
     scale_fill_manual(values=c('red','green'), breaks=c('w','v'))+ labs(title='TITLE',x = 'Year', y = 'Value')+
     facet_grid(. ~ Group)+ theme(axis.text.x = element_text(angle = 90, hjust = 1,size=11,margin = margin(b = 5)))

   print(g)
```

Plot with ggplot only

如果使用x轴标题,则与轴刻度标签重叠:

    ---
    title: |
      SLIDES
   author: |
      ME   
   date: |
      `r format(Sys.time(), '%d %B, %Y')`

   output: slidy_presentation
   runtime: knitr
   ---
```{r my.chunk, echo=FALSE, fig.width = 18, fig.height = 9, results='asis', message=FALSE}
   require(ggplot2)
   require(plotly)
   d<-data.frame(Year=rep(c(2020:2024),6),Group=rep(c('A','B','C'),each=10),Item=rep(c('w','v'),each=5),
                 Value=round(runif(30,100,500),0))
   g<-ggplot(d, aes(Year,Value,fill=Item ))+ 
     geom_bar( position = "stack", stat = "summary", fun.y = "sum",na.rm=T)+
     scale_y_continuous(labels = scales::comma) +
     scale_fill_manual(values=c('red','green'), breaks=c('w','v'))+ labs(title='TITLE',x = 'Year', y = 'Value')+
     facet_grid(. ~ Group)+ theme(axis.text.x = element_text(angle = 90, hjust = 1,size=11,margin = margin(b = 5)))

    ggplotly(g)%>%
    config(displayModeBar = FALSE) %>%
    layout(hovermode = 'compare')

enter image description here```

谢谢

1 个答案:

答案 0 :(得分:0)

最后我已经解决了

   g[['x']][['layout']][["annotations"]][[1]]$y<- -0.15

以g为情节对象

致谢