[英]Plotly/Dash leaving unexplained gaps in bar chart when Y contains negative and positive values
我正在開發一個 Web 應用程序,該應用程序繪制從 KenPom.com 抓取的大學籃球數據(可以在 kenpomgraphs.pythonanywhere.com 上看到)。 第一個圖是使用 px.bar() 的條形圖,它在大多數情況下都按預期工作。 但是,當我選擇包含 Y 的正值和負值的會議時,該數字在正條和負條之間留下了巨大的差距。
如果我將完全相同的代碼復制到 jupyter 筆記本中(用fig1.show()
替換return [fig1]
),我會得到所需的輸出。
這是生成圖形的代碼以及提供參數的回調。 df
是一個包含所有數據的數據框。 我根據提供給函數的參數將其過濾為dff
。 我嘗試添加諸如.reset_index()
和.copy()
認為可能是索引有問題或以某種方式引用了未過濾的數據幀,但這並沒有改變輸出。
@app.callback(
[Output('fig1', 'figure')],
[Input('stat-column', 'value'),
Input('number-teams', 'value'),
Input('conf', 'value')]
)
def update_figure_1(stat_column_name, number_teams, conf):
if stat_column_name == 'AdjD' or stat_column_name == 'OppD':
dff = df.loc[df['Conf'].isin(conf)].sort_values(by=stat_column_name, ascending=True).head(number_teams).reset_index().copy()
else: dff = df.loc[df['Conf'].isin(conf)].sort_values(by=stat_column_name, ascending=False).head(number_teams).reset_index().copy()
fig1 = px.bar(data_frame=dff,
x='Team',
y=stat_column_name,
color='Conf',
color_discrete_map=COLORS
)
fig1.update_traces(hovertemplate='%{x}: %{y}')
fig1.update_traces(marker=dict(line=dict(
width=2,
color='DarkSlateGrey')))
fig1.update_yaxes(range=[min(dff[stat_column_name]) - abs((min(dff[stat_column_name])*.2)), max(dff[stat_column_name])*1.15])
if stat_column_name == 'AdjD' or stat_column_name == 'OppD' or stat_column_name == 'Rk':
fig1.update_layout(xaxis_categoryorder = 'total ascending')
else: fig1.update_layout(xaxis_categoryorder = 'total descending')
fig1.update_layout(transition_duration=500)
fig1.update_yaxes(title=stat_column_name)
fig1.update_xaxes(title='')
return [fig1]
我正在使用 pythonanywhere 部署應用程序。 當我在 bash 控制台中執行代碼時,我可以確認dff
只包含我希望顯示的行,所以我不明白為什么會出現這個間隙,以及為什么在 jupyter 中運行時相同的代碼不會產生間隙筆記本。
我仍然不知道為什么存在差距,但我能夠通過刪除這些代碼行來解決問題:
if stat_column_name == 'AdjD' or stat_column_name == 'OppD' or stat_column_name == 'Rk':
fig1.update_layout(xaxis_categoryorder = 'total ascending')
else: fig1.update_layout(xaxis_categoryorder = 'total descending')
而是添加參數
category_orders={'Team': list(dff['Team'])}
到px.bar()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.