How to horizontally center a pie chart with plotly in R?

Viewed 581

I'm new to plotly, trying to figure out how to get a piechart to be aligned at the center of the entire plot area.

library(dplyr)
library(plotly)

data_for_plot <-
  mtcars %>%
  count(cyl)

> data_for_plot

##   cyl  n
## 1   4 11
## 2   6  7
## 3   8 14


plot_ly(data_for_plot, labels = ~cyl, values = ~n, type = 'pie', hole = 0.05 ,textposition = 'outside',textinfo = 'percent') %>%
  layout(title = list(text = "my nice title is here", xanchor = "center"),
         showlegend = F,
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE)) %>%
  layout(paper_bgcolor = "pink")

So I get this pie chart, which is not centered: plotly_piechart

I assume that inside layout() I need something that refers to the piechart itself, to assign it with xanchor = "center". But I researched this and couldn't find an answer.


Update on my attempts - 2020-01-18


I've tested the majority of attributes in layout() and still couldn't find something that would work with xanchor = "center". I've alse examined plotly's reference guide but so far to no avail.

1 Answers

Seems that the solution involves setting up the margin attribute within layout(). The solution is based on this hint, referring to this post. Implementing this to R is done using the following code:

plot_ly(data_for_plot, labels = ~cyl, values = ~n, type = 'pie', hole = 0.05 ,textposition = 'outside',textinfo = 'percent') %>%
  layout(title = list(text = "my nice title is here", xanchor = "center"),
         showlegend = F,
         margin = list(l = 20, r = 20),
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = TRUE)) %>%
  layout(paper_bgcolor = "pink")

pie_chart_centered

Related