简体   繁体   中英

How can I create a stacked bar graph for the WorldPhones dataset using plotly in R?

I need to make a bar graph for the WorldPhones dataset using R, using plotly , but I have had difficulties handling the data to make it a valid input in a stacked bar graph. The whole dataset is to be included in the graph.

Since I don't have details as to what you're looking for, you could probably use this to get started:

library(plotly)

# with the countries stacked by year:
df <- WorldPhones %>% as.data.frame() 
#      N.Amer Europe Asia S.Amer Oceania Africa Mid.Amer
# 1951  45939  21574 2876   1815    1646     89      555
# 1956  60423  29990 4708   2568    2366   1411      733
# 1957  64721  32510 5230   2695    2526   1546      773
# 1958  68484  35218 6662   2845    2691   1663      836
# 1959  71799  37598 6856   3000    2868   1769      911
# 1960  76036  40341 8220   3145    3054   1905     1008
# 1961  79831  43173 9053   3338    3224   2005     1076 


(fig <- plot_ly(df, x = ~row.names(df), y = ~N.Amer, type = 'bar', name = 'N. America') %>% 
  add_trace(y = ~Europe, name = 'Europe') %>% 
  add_trace(y = ~Asia, name = 'Asia') %>% 
  add_trace(y = ~S.Amer, name = "S. America") %>% 
  add_trace(y = ~Oceania, name = "Oceania") %>% 
  add_trace(y = ~Africa, name = "Africa") %>% 
  add_trace(y = ~Mid.Amer, name = "Mid America") %>% 
  layout(yaxis = list(title = "Count"), 
         xaxis = list(title = ""), 
         barmode = 'stack'))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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