繁体   English   中英

Plotly 堆叠条形图

[英]Plotly stacked bar chart

我可以请你帮忙吗? 我正在尝试使用此数据集的 plot_ly() 制作堆积条形图链接

但是,它不会产生所需的条形图。 首先,我只尝试了一个 bar plot 和下面的行(见下面的左手图表):

plotly::plot_ly(df, x=~TimePeriod, y=~round(DataValue_per_GDP*100,2), 
     color=~Sectors, type = "bar") %>% 
     layout(xaxis = list(title = ""), yaxis = list(title = "(% of GDP)"))

但是当我尝试将此代码制作为堆叠条形图时,数据会崩溃并且不会显示具有负值的时间序列,同时显示具有相反正弦值的时间序列,请参见下面的右侧图表

plotly::plot_ly(df, x=~TimePeriod, y=~round(DataValue_per_GDP*100,2), 
    color=~Sectors, type = "bar") %>% 
    layout(xaxis = list(title = ""), yaxis = list(title = "(% of GDP)"), barmode = 'stack')

我在这里做错了什么? 最后我需要一个堆积条形图。

在此处输入图像描述

barmode = 'stack'中,正值和负值相互重叠。

这是一个示例数据集:

df <- data.frame(TimePeriod = rep(as.Date(c("2022-01-01", "2022-01-02", 
                                            "2022-01-03", "2022-01-04",
                                            "2022-01-05")), 3),
                 DataValue_per_GDP = c(1, 3, 5, 4,7,
                                       3,-2, 1,-4,0,
                                       2, 3, 2,-1,1),
                 Sectors = rep(c(LETTERS[1:3]), each = 5))

对于日期“2022-01-02”,我们有以下值:

  TimePeriod DataValue_per_GDP Sectors
1 2022-01-02                 3       A
2 2022-01-02                -2       B
3 2022-01-02                 3       C

第一个条形图 A 从 0 开始到 3。条形图 B 从值 3 开始,然后向下两个值到 1。条形图 C 从 1 开始,然后从 3 个值开始到 4。所以条形图相互覆盖,结果看起来像这样:

在此处输入图像描述

要纠正此行为,请尝试barmode = 'relative'

plotly::plot_ly(df, 
                x=~TimePeriod, 
                y=~round(DataValue_per_GDP,2), 
                color=~Sectors, 
                type = "bar") %>% 
  layout(xaxis = list(title = ""), 
         yaxis = list(title = "(% of GDP)"), 
         barmode = 'relative')

在此处输入图像描述

使用pivot_wider重塑数据后,我们可以对不同的列使用add_trace

library(plotly)
library(dplyr)
library(tidyr)

df1 <- df %>%
  mutate(Sectors = trimws(Sectors)) %>% 
  pivot_wider(names_from = Sectors, values_from = DataValue_per_GDP) 

fig <- plotly::plot_ly(df1, x=~TimePeriod, y=~round(`C. External`*100,2), 
                type = "bar", name="C. External") %>% 
  add_trace(y = ~`B. Private`, name = 'B. Private') %>% 
  add_trace(y = ~`A. General government`, name = 'A. General government') %>% 
  layout(yaxis = list(title = '(% of GDP)'), barmode = 'stack')
fig

在此处输入图像描述

暂无
暂无

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

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