简体   繁体   English

如何在 R 中将带有 plotly 的饼图水平居中?

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

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.我是 plotly 的新手,试图弄清楚如何让饼图在整个 plot 区域的中心对齐。

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" .我假设在layout()内部我需要一些引用饼图本身的东西,用xanchor = "center"分配它。 But I researched this and couldn't find an answer.但是我对此进行了研究,但找不到答案。


Update on my attempts - 2020-01-18我的尝试更新 - 2020-01-18


I've tested the majority of attributes in layout() and still couldn't find something that would work with xanchor = "center" .我已经测试了layout()中的大多数属性,但仍然找不到可以与xanchor = "center"一起使用的东西。 I've alse examined plotly's reference guide but so far to no avail.我还检查了plotly 的参考指南,但到目前为止无济于事。

Seems that the solution involves setting up the margin attribute within layout() .似乎解决方案涉及在layout()中设置margin属性。 The solution is based on this hint , referring to this post .解决方案是基于这个提示,参考这篇文章 Implementing this to R is done using the following code:使用以下代码将其实现到R

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

饼图居中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM