首页 > 解决方案 > plotly.figure_factory.create_annotated_heatmap 未正确显示带有轴标签的图形

问题描述

我想在带有注释的 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)
    
    
    ```

标签: pythonplotlyheatmapplotly-dash

解决方案


我无法复制您的确切问题,但我见过类似的

试试: fig.update_xaxes(type='category')

如果 Plotly 认为它可以强制你的轴是“线性的”,它会在后台做一些工作。型号标签可以避免这种情况。

这里的一些背景 Plotly Categorical Axes


推荐阅读