簡體   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