Plotly figure_factory热图y轴字符串标签误识别为整数,autotypenumbers不生效?
问题根因
ff.create_annotated_heatmap 函数内部生成图表时会优先自动推断轴类型,即便后续手动设置轴为分类类型、传入autotypenumbers="strict",也因为推断步骤已经完成,参数无法生效。Plotly会自动将可转为整数的字符串标签按数值排序,导致和原数据的行顺序不匹配,出现标签错位、重叠、空行的问题。
解决方案1(无需修改原标签,兼容性最好)
直接手动指定Y轴的分类序列和顺序,完全跳过自动推断逻辑,仅需修改你原有代码中Y轴的配置部分即可:
import plotly.figure_factory as ff z_values = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16], [17,18,19,20], [21,22,23,24],] x_values = ['A', 'B', 'C', 'D'] y_values = ['<2', '2', '3', '4', '5', '6<='] y_values.reverse() z_labels = z_values fig = ff.create_annotated_heatmap( z=z_values, x=x_values, y=y_values, colorscale='Bluyl', annotation_text=z_labels ) fig.update_layout(autotypenumbers="strict") fig.update_xaxes({'type': 'category', 'autotypenumbers': 'strict', 'title': {'text': 'Test label'}}) # 修改Y轴配置,新增分类顺序指定 fig.update_yaxes({ 'type': 'category', 'autotypenumbers': 'strict', 'title': {'text': 'Test label'}, # 新增以下两行,直接使用你定义的y_values顺序作为轴标签顺序 'categoryorder': 'array', 'categoryarray': y_values }) fig.show()
解决方案2(让autotypenumbers参数生效)
autotypenumbers参数需要在轴类型推断前传入才会生效,figure_factory接口没有暴露这个初始化参数,可以改用plotly.graph_objects实现带标注的热图,创建图表时就传入配置:
import plotly.graph_objects as go fig = go.Figure(data=go.Heatmap( z=z_values, x=x_values, y=y_values, colorscale='Bluyl', text=z_labels, texttemplate="%{text}" )) fig.update_layout(autotypenumbers="strict") fig.update_yaxes(type='category', title_text='Test label') fig.update_xaxes(type='category', title_text='Test label') fig.show()
内容的提问来源于stack exchange,提问作者PL2021
相关产品推荐
相关产品推荐

