簡體   English   中英

如何使用 plotly.express 在頂部創建帶有共享 x 軸的條形 plot?

[英]How to create a bar plot with shared x-axis using plotly.express with sub-titles on top?

我想知道如何在 plotly 中正確創建一個帶有共享 x 軸的條形 plot? 我創建了這個欄 plot 並指定fig.update_xaxes(matches='x') ,據我所知,它應該與軸匹配,但顯然這不起作用。 這看起來像一個錯誤還是我做錯了什么? 如您所見,除了一個完全關閉的子圖外,它看起來不錯。 有時,使用facet_row代替facet_col會得到更好的結果,但隨后標題出現在 plot 的側面。 標題有時很長,不適合在那里。 因此,我正在使用facet_col

fig = px.bar(data_frame=df, x='RawFile', y=plot_column, 
             facet_col='Majority protein IDs', facet_col_wrap=1, color=color, 
             color_discrete_sequence=px.colors.qualitative.Dark24,
             color_continuous_scale=px.colors.sequential.Rainbow)

n_rows = len(df['Majority protein IDs'].drop_duplicates())

height = 300*(1+n_rows)

fig.update_layout(
        height=height,        
        margin=dict( l=50, r=10, b=200, t=50, pad=0 ),
        hovermode='closest')

fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.update(layout_showlegend=True)
fig.update_xaxes(matches='x')

在此處輸入圖像描述

奇怪的是, y-axes是共享的,但x-axes不是。 這與我正在尋找的完全相反。

在此處輸入圖像描述

# django-plotly-dash        1.6.3
# plotly                    4.14.3

我想對此的一種解決方案是使用facet_row但是,然后我需要將標題從右側移動到頂部。

我的理解是,您希望所有 plot 標題出現在所有子圖的頂部。 plotly express 似乎沒有任何內置功能可以做到這一點。 您總是可以調整圖形的元素,但在這種情況下有點棘手,因為您必須調整所有子圖的高度才能為標題騰出空間。 到目前為止,這是我對示例數據集的最佳嘗試:

在此處輸入圖像描述

如果這是你可以使用的東西,我們可以仔細看看細節。

完整代碼:

import plotly.express as px
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", facet_row="sex")
f = fig.full_figure_for_development(warn=False)

yrefs = []
for i, elem in enumerate(fig.layout):
    if elem[:5] == 'yaxis':
        yrefs.append(fig.layout[elem].domain[1])

for i, title in enumerate(fig.layout.annotations):
    title.textangle = 0
    title.y = yrefs[i] - 0.03
#     title.x = 0.5 - ((len(title.text)+1) / 100)
    title.x = 0.40
    title.align = 'center'
    title.bgcolor='rgba(0,0,0,0.25)'
    
fig.show()

暫無
暫無

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

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