1

Axis title overlaps axis ticks when use plotly inside rmarkdown. i've tried Plot margins in RMarkdown/knitr, R: ggplot and plotly axis margin won't change and Y Axis - Margin Size. No success. Show you my code:

only ggplot works fine:

    ---
    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

If use plotly x axis title overlaps axis ticks labels:

    ---
    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 ```

thanks

pogibas
  • 27,303
  • 19
  • 84
  • 117

1 Answers1

2

Finally i've solved using

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

with g as plotly object

Regards

  • Where did you find this, I have been trying to solve this for so long. Can you explain it a little? – Bryan Butler Jan 29 '21 at 16:07
  • Excuses for taking so long to respond, but I was offline for a long period. I solved the issue from https://stackoverflow.com/questions/42763280/r-ggplot-and-plotly-axis-margin-wont-change What I can understand is that it is about modifying properties of the plotly object, in this case, Y position of the label that contains the title on the X axis. – José Fernando Giraldo Jimenez Jun 30 '21 at 14:09