Python热图表着色问题

时间:2017-06-09 15:55:37

标签: python pandas flask heatmap

我正在尝试制作一个可以在html中读取的热图,它当前正在正确输出数据,但热图着色是基于每列中的最大值而不是数据中的最大值我不确定如何改变这一点,以便热图基于所有数据。

from flask import *
import pandas as pd
import seaborn as sns

app = Flask(__name__)

@app.route("/Matrix")
def show_tables():
    cm = sns.light_palette("red", as_cmap=True)
    df = pd.read_csv('matrix.csv', header=0, index_col=0, na_filter=False)
    df = df.sort_index(ascending=False)
    html = (df.style.background_gradient(cmap=cm).render())
    return render_template('view.html', tables=[html])
if __name__ == "__main__":
    app.run(debug=True)

热图表输出:

Heatmap Table Output

1 个答案:

答案 0 :(得分:1)

您希望脱离正在进行的操作,并阅读pandashttp://pandas.pydata.org/pandas-docs/stable/style.html)的样式文档

简而言之,您需要编写自己的样式函数(从文档中修改)

import pandas as pd
import numpy as np
import seaborn as sns

df = pd.DataFrame(np.random.random(size=(10, 5)))

def highlight_max(data):
    cm = sns.light_palette("red", as_cmap=True)

    # have to convert the color map colors to hex values for the CSS to work
    # if you have a better way of doing the RGBA -> HEX conversion use that
    # this is awful but works
    hex_colors = ['#{:02x}{:02x}{:02x}'.format(*(np.asarray(cm(v)) * 255).astype(int)) for v in data.values.ravel()]
    colors = ['background-color: {}'.format(h) for h in hex_colors]
    return pd.DataFrame(np.asarray(colors).reshape(*data.shape),
                        index=data.index,
                        columns=data.columns)


df.style.apply(highlight_max, axis=None) # axis none to apply to whole DF in one go