簡體   English   中英

將Y軸添加到plotly.express bar plot

[英]adding Y axis to plotly.express bar plot

我想在下面的條形 plot 中添加第二個 Y 軸,即 integer 中的公民人數: 在此處輸入圖像描述

此圖是使用 plotly 制作的:

import plotly.express as px

fig = px.bar(df, x="country",y="pourcent_visit",color="city",barmode='group')
# fig.add_hline(y=10)

fig.show() 

據我所知,沒有直接的方法可以做到這一點。 但是您可以輕松地構建一個Plotly Express圖形,從那里抓取軌跡(和數據結構),然后使用fig = make_subplots(specs=[[{"secondary_y": True}]])將它們組合成一個允許多個軸的圖形。 在沒有提供數據樣本的情況下,我將使用內置數據集px.data.tips() ,我猜這在很大程度上類似於您在應用 arguments 的方式來判斷您的真實世界數據集的結構px.bar() 評論中的詳細信息,但如果有不清楚的地方,請隨時告訴我。

Plot:

在此處輸入圖像描述

完整代碼:

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

# sample data
df = px.data.tips()

# figure setup with multiple axes
fig = make_subplots(specs=[[{"secondary_y": True}]])

# build plotly express plot
fig2 = px.bar(df, x="day", y="total_bill", color="smoker", barmode="group")

# add traces from plotly express figure to first figure
for t in fig2.select_traces():
    fig.add_trace(t, secondary_y = False)
    
# handle data for secondary axis
df2 = df.groupby('day').agg('sum')#.reset_index()
df2 = df2.reindex(index = df['day'].unique()).reset_index()

# 
fig.add_trace(go.Scatter(x = df2['day'], y = df2['size'], mode = 'lines'), secondary_y = True)

# fix layout
fig.update_layout(legend_title_text = 'smoker')

fig.show()

暫無
暫無

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

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