【问题标题】:plotly.figure_factory.create_annotated_heatmap doesn't show figure with axis labels correctlyplotly.figure_factory.create_annotated_heatmap 没有正确显示带有轴标签的图形
【发布时间】:2021-07-24 17:00:06
【问题描述】:

我想在带有注释的 Plotly Dash 应用程序中显示带注释的热图。热图工作得很好,如果我没有添加轴标签,或者标签不仅仅是只有数字的字符串,但如果我添加了轴标签,数字太小并且注释显示不正确。@987654321 @

我在 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)
    
    
    ```

【问题讨论】:

    标签: python plotly heatmap plotly-dash


    【解决方案1】:

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

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

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

    这里有一些背景 Plotly Categorical Axes

    【讨论】:

    • 我再次尝试使用类别,我遇到了同样的问题,事实上我已经尝试了plotly.com/python/categorical-axes 中的所有可能性,但仍然有同样的问题
    【解决方案2】:

    这是一个错误。问题出在幕后运行的“_AnnotatedHeatmap”类(非常肯定)中。 'create_annotated_heatmap' 函数不是一个非常智能 的函数。如果您查看代码,它会非常简单(在我看来,它更像是一种快速而肮脏的解决方案,而不是彻底开发的流线型情节)。我没有费心去解决它,只是解决了问题。这是我的解决方案:

    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()
    

    这个解决方法的问题是内置的数据到轴的映射不会发生。您必须自己映射数据。 确保您对坐标轴进行排序,并且也以这种方式对数据进行排序!我尚未验证它是否正确映射了数据,但我认为确实如此。为了缓解这个问题,这是我为此编写的代码:

    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])
    

    像泥一样清澈?希望我输入正确。如果没有,请在 cmets 中告诉我。我确信最后一点代码可以改进,所以如果你知道如何,请随时在评论中留下它,我会更新它。

    【讨论】:

      猜你喜欢
      • 2019-03-02
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多