可视化篇(五)——— python绘制热力图及案例
生活随笔
收集整理的這篇文章主要介紹了
可视化篇(五)——— python绘制热力图及案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
可視化篇(五)——— python繪制熱力圖及案例
- 摘要
- 效果圖
- python代碼
摘要
本文演示了如何通過python繪制熱力圖,并給出了其應用于展示數據之間相關性的案例供讀者參考。
效果圖
python代碼
from matplotlib import font_manager import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pdclass CyrusPlot(object):def __init__(self,dpi=72,fig_size=[30,20]):"""實列化該類,然后直接調用cyrus_heat_map方法:param dpi::param fig_size:"""self.dpi = dpiself.fig_size = fig_sizeself.font = font_manager.FontProperties(fname="C:\Windows\Fonts\simhei.ttf", size=30)def cyrus_heat_map(self,datas,x_ticks = [],y_ticks = [],bar_label = "bar label",show = True,save_name = ""):figure = plt.figure(figsize=self.fig_size, dpi=self.dpi)ax = figure.add_subplot(111)if not x_ticks:x_ticks = ["x"+str(i) for i in range(datas.shape[1])]y_ticks = ["y" + str(i) for i in range(datas.shape[0])]im, _ = self.heatmap(np.array(datas), x_ticks, y_ticks,cmap="RdBu", cbarlabel=bar_label,ax=ax) # plt.cm.RdBu PuOrself.annotate_heatmap(im, valfmt="{x:.2f}", size=16)if save_name:plt.savefig("./figure/" + save_name + ".jpg")if show:plt.show()def heatmap(self,data, row_labels, col_labels, ax=None,cbar_kw={}, cbarlabel="", **kwargs):if not ax:ax = plt.gca()im = ax.imshow(data, **kwargs)cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)cbar.ax.set_ylabel(cbarlabel, rotation=-90, va="bottom",fontproperties=font_manager.FontProperties(fname="C:\Windows\Fonts\simhei.ttf", size=30))ax.set_xticks(np.arange(data.shape[1]))ax.set_yticks(np.arange(data.shape[0]))ax.set_xticklabels(col_labels,fontproperties=self.font)ax.set_yticklabels(row_labels,fontproperties=self.font)ax.tick_params(top=True, bottom=False,labeltop=True, labelbottom=False)plt.setp(ax.get_xticklabels(), rotation=-30, ha="right",rotation_mode="anchor")for edge, spine in ax.spines.items():spine.set_visible(False)ax.set_xticks(np.arange(data.shape[1] + 1) - .5, minor=True)ax.set_yticks(np.arange(data.shape[0] + 1) - .5, minor=True)ax.grid(which="minor", color="w", linestyle='-', linewidth=3)ax.tick_params(which="minor", bottom=False, left=False)return im, cbardef annotate_heatmap(self,im, data=None, valfmt="{x:.2f}",textcolors=("black", "white"),threshold=None, **textkw):if not isinstance(data, (list, np.ndarray)):data = im.get_array()if threshold is not None:threshold = im.norm(threshold)else:threshold = im.norm(data.max()) / 2.kw = dict(horizontalalignment="center",verticalalignment="center",)kw.update(textkw)if isinstance(valfmt, str):valfmt = matplotlib.ticker.StrMethodFormatter(valfmt)texts = []for i in range(data.shape[0]):for j in range(data.shape[1]):kw.update(color=textcolors[abs(data[i, j]) > 0.5])text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)texts.append(text)return texts實列化該類,然后直接調用cyrus_heat_map方法。
if __name__ == '__main__':# 構造數據集并計算其pearson相關系數data = pd.DataFrame(np.random.randn(10,10))pearson = data.corr()plot_tool = CyrusPlot()plot_tool.cyrus_heat_map(pearson,show=True)by CyrusMay 2021 01 27
看過多少臉龐
飛過多少異鄉
少年早已蒼茫
少年早已蒼茫
回頭望
回頭望
我在何方
——————五月天(成名在望)——————
總結
以上是生活随笔為你收集整理的可视化篇(五)——— python绘制热力图及案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 可视化篇(四)——— python绘制双
- 下一篇: Git篇——Git使用教程