How to plot a nested pie chart using plotly in R?

一世执手 提交于 2020-06-26 05:33:29

问题


I am trying to plot a nested pie chart, but the output didn't reflect the reality.

Let's say:

library('plotly')
library('dplyr')

data <- data.frame(c('cat', 'dog', 'deer','chicken', 'cat', 'dog','duck', 'monkey', 'fish','cow','horse','dog'),c('US', 'US', 'US','US', 'UK', 'UK','UK', 'UK','China','China','China','China'),c(15,70,120,55,47,300,89,62,40,27,103,8))
colnames(data) <- c('animal', 'country', 'total_num')

p <- plot_ly(data) %>% add_pie(labels = ~animal, values = ~total_num, type = 'pie', hole = 0.7, sort = F) %>% add_pie(data, labels = ~country, values = ~total_num, domain = list(x = c(0.15, 0.85),y = c(0.15, 0.85)),sort = F)

p

The resulted pie chart is misleading as it supposed to have distribution of the animals according to each country, the distribution should be dependent on the country. But the shown pie charts are showing individual distribution. I am struggling in getting this using plotly.

Any suggestions or help will be very much appreciated.

Thanks!


回答1:


Let's ignore the whole question if one should but answer how one could create a nested pie chart.

You could create two pie charts, the outer one is a donut chart, i.e. by setting hole = 0.7 and the inner chart is a subplot which has set the domain.

library('plotly')
library('dplyr')

data <- data.frame(c('cats', 'monkeys', 'dogs'), c(30, 10, 20), c(20, 10, 10))
colnames(data) <- c('animal', 'street', 'home')

p <- plot_ly(data) %>%
  add_pie(labels = ~animal, values = ~street, type = 'pie', hole = 0.7, sort = F) %>%
  add_pie(data, labels = ~animal, values = ~home, 
          domain = list(
            x = c(0.15, 0.85),
            y = c(0.15, 0.85)),
          sort = F)
p



来源:https://stackoverflow.com/questions/50824018/how-to-plot-a-nested-pie-chart-using-plotly-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!