[英]plotly.figure_factory.create_annotated_heatmap doesn't show figure with axis labels correctly
我想在带有注释的 Plotly Dash 应用程序中显示带注释的热图。 如果我没有添加轴标签,或者标签不仅仅是只有数字的字符串,但如果我添加了轴标签,则热图工作得非常好,数字太小并且注释显示不正确。
我在 Dash 中创建了一个简单的示例来说明我的问题。
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objects as go
import plotly.figure_factory as ff
import numpy as np
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')
app.layout = html.Div([
dcc.Graph(id='graph-with-slider'),
dcc.Slider(
id='year-slider',
min=df['year'].min(),
max=df['year'].max(),
value=df['year'].min(),
marks={str(year): str(year) for year in df['year'].unique()},
step=None
)
])
@app.callback(
Output('graph-with-slider', 'figure'),
Input('year-slider', 'value'))
def update_figure(selected_year):
y = ['8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
x = ["023", "034", "045", "056", "067", "078"]
z = [[4, 4, 2, 1, 0, 0],
[0, 0, 0, 0, 0, 0],
[11, 2, 4, 0, 0, 1],
[np.nan, 0, 0, 0, 0, 0],
[8, 1, 6, 1, 32, 3],
[5, 0, 0, 5, 0, 0],
[0, 0, 0, 0, 0, 0],
[24, 2, 15, 1, 0, 5],
[0, 0, 0, 0, 0, 0],
[0, 0, 8, 0, 7, 0],
[0, 0, 0, 9, 0, 0]]
## it will work if i enabaled the next two lines of code
# or if axis labels where just numbers and not something like "032"
#x=["add any non numerical string and it will work" + s for s in x]
#y=["add any non numerical string and it will work" + s for s in y]
#fig = go.Figure(data=go.Heatmap(z=z))
fig =ff.create_annotated_heatmap(z=z,x=x,y=y, colorscale = ["green", "yellow", "orange", "red"], showscale = True)
layout = go.Layout(width=500, height=500,
hovermode='closest',
autosize=True,
xaxis=dict(zeroline=False),
yaxis=dict(zeroline=False, autorange='reversed')
)
fig = go.Figure(data=fig, layout=layout)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
```
我无法复制您的确切问题,但我见过类似的
试试: fig.update_xaxes(type='category')
如果 Plotly 认为它可以强制您的轴为“线性”,它会在后台执行一些工作。 label 类型可以避免这种情况。
这里有一些背景Plotly 分类轴
这是一个错误。 问题出在幕后操作的“_AnnotatedHeatmap”class(非常肯定)中。 'create_annotated_heatmap' function 不是一个非常智能的 function。 如果您查看代码,它出奇地简单(在我看来,它更像是一个快速而肮脏的解决方案,而不是彻底开发的流线型 plotly 东西)。 我没有费心去解决它,只是解决了问题。 这是我的解决方案:
fig = ff.create_annotated_heatmap(z=z,
colorscale='greens')
fig.update_layout(overwrite=True,
xaxis=dict(ticks="", dtick=1, side="top", gridcolor="rgb(0, 0, 0)", tickvals=list(range(len(x))), ticktext=x)
yaxis=dict(ticks="", dtick=1, ticksuffix=" ", tickvals=list(range(len(y))), ticktext=y))
fig.show()
这种解决方法的问题是内置的数据到轴的映射不会发生。 您必须自己 map 数据。 确保您对轴进行排序,并且也以这种方式对数据进行排序!! 我尚未验证它是否正确映射了数据,但我认为确实如此。 为了缓解这个问题,这是我为此编写的代码:
x = list(sorted(df['X'].unique().tolist()))
y = list(sorted(df['Y'].unique().tolist()))
z = list()
iter_list = list()
for y_item in y:
iter_list.clear()
for x_item in x:
z_data_point = df[(df['X'] == x_item) & (df['Y'] == y_item)]['Z']
iter_list.append(0 if len(z_data_point) == 0 else z_data_point.iloc[0])
z.append([_ for _ in iter_list])
清如泥? 希望我输入正确。 如果没有,请在评论中告诉我。 我确信这最后一点代码可以改进,所以如果你知道如何,请随时将它留在评论中,我会更新它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.