簡體   English   中英

plotly:添加框 plot 作為子圖

[英]plotly: add box plot as subplot

我正在嘗試創建一個可視化效果,其中餅圖出現在頂部,框 plot 出現在下方。 我正在使用 plotly 庫。

我嘗試使用此代碼:

import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(
    rows=2, cols=1,
    specs=[[{'type':'pie'}], [{'type':'box'}]],
)

# pie chart
pie = go.Pie(values=[1, 2, 3, 4, 5], labels=['a', 'b', 'a', 'a', 'c'], sort=False)

# box plot
import numpy as np
np.random.seed(1)

y0 = [10, 1, 2, 3, 1, 5, 8, 2]
y1 = [10, 1, 2, 3, 1, 5, 8, 2]

box = go.Figure()
box.add_trace(go.Box(y=y0))
box.add_trace(go.Box(y=y1))

# add pie chart and box plot to figure
fig.add_trace(pie, row=1, col=1)
fig.add_trace(box, row=2, col=1)
fig.update_traces(textposition='inside', textinfo='percent+label')

fig.show()

但是,我遇到了這個錯誤:

Invalid element(s) received for the 'data' property of
        Invalid elements include: [Figure({
    'data': [{'type': 'box', 'y': [10, 1, 2, 3, 1, 5, 8, 2]}, {'type': 'box', 'y': [10, 1, 2, 3, 1, 5, 8, 2]}],
    'layout': {'template': '...'}
})]

你的代碼有兩個錯誤

  1. box創建為圖形。 add_trace()添加軌跡而不是圖形。 更改為循環遍歷方框圖box的跡線
  2. update_traces()正在更新Box跟蹤中不存在的屬性。 更改為使用for_each_trace()並更新對跟蹤類型有效的屬性

完整代碼

import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(
    rows=2,
    cols=1,
    specs=[[{"type": "pie"}], [{"type": "box"}]],
)

# pie chart
pie = go.Pie(values=[1, 2, 3, 4, 5], labels=["a", "b", "a", "a", "c"], sort=False)

# box plot
import numpy as np

np.random.seed(1)

y0 = [10, 1, 2, 3, 1, 5, 8, 2]
y1 = [10, 1, 2, 3, 1, 5, 8, 2]

box = go.Figure()
box.add_trace(go.Box(y=y0))
box.add_trace(go.Box(y=y1))

# add pie chart and box plot to figure
fig.add_trace(pie, row=1, col=1)
# fig.add_trace(box, row=2, col=1)
for t in box.data:
    fig.add_trace(t, row=2, col=1)
# fig.update_traces(textposition='inside', textinfo='percent+label')
fig.for_each_trace(
    lambda t: t.update(textposition="inside", textinfo="percent+label")
    if isinstance(t, go.Pie)
    else t
)


fig.show()

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM