日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

可视化篇(五)——— python绘制热力图及案例

發布時間:2025/3/21 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 可视化篇(五)——— 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绘制热力图及案例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。