【问题标题】:figure_factory heatmap figure labels incorrectly applied to integer y-axis values (autotypenumbers not working?)figure_factory 热图图形标签错误地应用于整数 y 轴值(自动输入编号不起作用?)
【发布时间】:2025-11-24 14:55:01
【问题描述】:

我正在尝试使用 plotly figure_factory 创建带注释的热图。所有的 y 标签都是字符串,但有些可以解释为整数。该图似乎自动将一些轴标签解释为整数,然后错误地重新排序图表值。您可以看到其中一行根本没有标签,而另一行有两个标签,一个在另一个之上。

我尝试应用 autotypenumbers="strict" 认为它会有所帮助,但它没有奏效。当我将一些字符(例如“-”)附加到 y 标签列表时,问题就解决了,因为标签不再被解释为整数。我宁愿不依赖这样的解决方法。

有没有办法将自动类型编号应用于图形来解决问题?还有其他解决方案吗? (下面的数据是虚拟数据 - 忽略 x 和 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'}}) fig.update_yaxes({'type': 'category', 'autotypenumbers': 'strict', 'title': {'text': 'Test label'}})

fig.show()

enter image description here

【问题讨论】:

    标签: python plotly heatmap


    【解决方案1】:

    带注释的热图存在许多问题,开发社区表示没有足够的时间和资源来改进它们。此评论来自here。此外,此问题可以通过将 y 轴创建为数值并随后替换为 y 轴显示字符串的技术来解决。解决方法我参考了this

    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 = [0,1,2,3,4,5]
    # 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_yaxes(tickvals=[0,1,2,3,4,5], ticktext=['<2', '2', '3', '4', '5', '6<='])
    
    fig.show()
    

    【讨论】:

    • 如果你在 Github 问题中搜索带注释的热图,你会发现很多贡献。如果您觉得我的回答有帮助,请点击对勾接受我的回答。