search
HomeBackend DevelopmentPython TutorialHow to implement visual heat map in python

How to implement visual heat map in python

Apr 04, 2018 pm 02:22 PM
pythonVisualizationheat map


This article mainly introduces how to implement visual heat map in python. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look

Heat map

1. Use heat map to see the similarity of multiple features in the data table. Refer to the official API parameters and address:

seaborn.heatmap(data, vmin=None, vmax=None,cmap=None, center=None, robust=False, annot=None, fmt ='.2g', annot_kws=None,linewidths=0, linecolor='white', cbar=True, cbar_kws=None, cbar_ax=None,square=False, xticklabels='auto', yticklabels='auto', mask= None, ax=None,**kwargs)

(1) Heat map input data parameters:

data: Matrix data set, yes It is an array of numpy, or it can be a DataFrame of pandas. If it is a DataFrame, the index/column information of df will correspond to the columns and rows of the heatmap respectively, that is, pt.index is the row label of the heat map, and pt.columns is the column label of the heat map

(2) Heat map matrix block color parameters:

vmax, vmin: are the maximum and minimum color value ranges of the heat map respectively. The default is determined based on the values ​​in the data table
cmap: Mapping from numbers to color space, the value is the colormap name or color object in the matplotlib package, or a list representing colors; change the parameter default value: set according to the center parameter
center: When the data table values ​​are different, set the color center alignment value of the heat map; by setting the center value, you can adjust the overall depth of the generated image color; when setting the center data, if there is data overflow, manually The set vmax and vmin will automatically change
robust: The default value is False; if it is False and the values ​​​​of vmin and vmax are not set, the color mapping range of the heat map is based on the robustness Quantile setting, instead of extreme value setting

(3) Heat map matrix block annotation parameters:

annot (abbreviation of annotate): default Value False; if it is True, data is written in each square of the heat map; if it is a matrix, data corresponding to the matrix is ​​written in each square of the heat map
fmt: String format Code, data format for identifying numbers on the matrix, such as retaining several digits after the decimal point
annot_kws: Default value is False; if it is True, set the size, color, and font of the numbers on the heat map matrix, matplotlib package Font settings under the text class; official document:

(4) Spacing and spacing line parameters between heat map matrix blocks:

linewidths: Define the " The gap size between "matrix patches" that represent pairwise feature relationships
linecolor: The color of the line that divides each matrix patch on the heat map. The default value is 'white'

(5) Heat map color scale bar parameters:

cbar: Whether to draw a color scale bar on the side of the heat map. The default value is True
cbar_kws: When drawing color scale bars on the side of the heat map, the relevant font settings, the default value is None
cbar_ax: When drawing the color scale bars on the side of the heat map, the scale bar position settings, the default value is None

(6) square: Set the shape of the heat map matrix, the default value is False

xticklabels, yticklabels:xticklabels controls each column Output of label names; yticklabels controls the output of label names for each line. The default value is auto. If True, the column name of the DataFrame is used as the label name. If False, no row label names are added. If it is a list, the label name is changed to the content given in the list. If it is an integer K, label every K labels on the graph. If it is auto, the label spacing of the labels will be automatically selected, and the non-overlapping part (or all) of the label names will be output.
mask: Controls whether a certain matrix block is displayed. The default value is None. If it is a Boolean DataFrame, cover the True position in the DataFrame with white
ax: Set the coordinate axis of the drawing. Generally, when drawing multiple subgraphs, you need to modify the coordinates of different subgraphs. Value
**kwargs:All other keyword arguments are passed to ax.pcolormesh

Heat map matrix block color parameters

#cmap(颜色)

import matplotlib.pyplot as plt
% matplotlib inline

f, (ax1,ax2) = plt.subplots(figsize = (6,4),nrows=2)

# cmap用cubehelix map颜色
cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)
sns.heatmap(pt, linewidths = 0.05, ax = ax1, vmax=900, vmin=0, cmap=cmap)
ax1.set_title('cubehelix map')
ax1.set_xlabel('')
ax1.set_xticklabels([]) #设置x轴图例为空值
ax1.set_ylabel('kind')

# cmap用matplotlib colormap
sns.heatmap(pt, linewidths = 0.05, ax = ax2, vmax=900, vmin=0, cmap='rainbow') 
# rainbow为 matplotlib 的colormap名称
ax2.set_title('matplotlib colormap')
ax2.set_xlabel('region')
ax2.set_ylabel('kind')

How to implement visual heat map in python

#center的用法(颜色)f, (ax1,ax2) = plt.subplots(figsize = (6, 4),nrows=2)

cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)
sns.heatmap(pt, linewidths = 0.05, ax = ax1, cmap=cmap, center=None )
ax1.set_title('center=None')
ax1.set_xlabel('')
ax1.set_xticklabels([]) #设置x轴图例为空值ax1.set_ylabel('kind')# 当center设置小于数据的均值时,生成的图片颜色要向0值代表的颜色一段偏移sns.heatmap(pt, linewidths = 0.05, ax = ax2, cmap=cmap, center=200)   
ax2.set_title('center=3000')
ax2.set_xlabel('region')
ax2.set_ylabel('kind')

How to implement visual heat map in python

#robust的用法(颜色)f, (ax1,ax2) = plt.subplots(figsize = (6,4),nrows=2)

cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)

sns.heatmap(pt, linewidths = 0.05, ax = ax1, cmap=cmap, center=None, robust=False )
ax1.set_title('robust=False')
ax1.set_xlabel('')
ax1.set_xticklabels([]) #设置x轴图例为空值ax1.set_ylabel('kind')

sns.heatmap(pt, linewidths = 0.05, ax = ax2, cmap=cmap, center=None, robust=True ) 
ax2.set_title('robust=True')
ax2.set_xlabel('region')
ax2.set_ylabel('kind')

How to implement visual heat map in python

Heat map matrix block annotation parameters

#annot(矩阵上数字),annot_kws(矩阵上数字的大小颜色字体)matplotlib包text类下的字体设置import numpy as np
np.random.seed(20180316)
x = np.random.randn(4, 4)

f, (ax1, ax2) = plt.subplots(figsize=(6,6),nrows=2)

sns.heatmap(x, annot=True, ax=ax1)

sns.heatmap(x, annot=True, ax=ax2, annot_kws={'size':9,'weight':'bold', 'color':'blue'})# Keyword arguments for ax.text when annot is True.  http://stackoverflow.com/questions/35024475/seaborn-heatmap-key-words

How to implement visual heat map in python

#fmt(字符串格式代码,矩阵上标识数字的数据格式,比如保留小数点后几位数字)import numpy as np
np.random.seed(0)
x = np.random.randn(4,4)

f, (ax1, ax2) = plt.subplots(figsize=(6,6),nrows=2)

sns.heatmap(x, annot=True, ax=ax1)

sns.heatmap(x, annot=True, fmt='.1f', ax=ax2)

How to implement visual heat map in python

热力图矩阵块之间间隔及间隔线参数

#linewidths(矩阵小块的间隔),linecolor(切分热力图矩阵小块的线的颜色)import matplotlib.pyplot as plt
f, ax = plt.subplots(figsize = (6,4))
cmap = sns.cubehelix_palette(start = 1, rot = 3, gamma=0.8, as_cmap = True)   
sns.heatmap(pt, cmap = cmap, linewidths = 0.05, linecolor= 'red', ax = ax)   
ax.set_title('Amounts per kind and region')
ax.set_xlabel('region')
ax.set_ylabel('kind')

How to implement visual heat map in python

#xticklabels,yticklabels横轴和纵轴的标签名输出import matplotlib.pyplot as plt
f, (ax1,ax2) = plt.subplots(figsize = (5,5),nrows=2)

cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)

p1 = sns.heatmap(pt, ax=ax1, cmap=cmap, center=None, xticklabels=False)
ax1.set_title('xticklabels=None',fontsize=8)

p2 = sns.heatmap(pt, ax=ax2, cmap=cmap, center=None, xticklabels=2, yticklabels=list(range(5))) 
ax2.set_title('xticklabels=2, yticklabels is a list',fontsize=8)
ax2.set_xlabel('region')

How to implement visual heat map in python

#mask对某些矩阵块的显示进行覆盖

f, (ax1,ax2) = plt.subplots(figsize = (5,5),nrows=2)

cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)

p1 = sns.heatmap(pt, ax=ax1, cmap=cmap, xticklabels=False, mask=None)
ax1.set_title('mask=None')
ax1.set_ylabel('kind')

p2 = sns.heatmap(pt, ax=ax2, cmap=cmap, xticklabels=True, mask=(pt<800))   
#mask对pt进行布尔型转化,结果为True的位置用白色覆盖
ax2.set_title(&#39;mask: boolean DataFrame&#39;)
ax2.set_xlabel(&#39;region&#39;)
ax2.set_ylabel(&#39;kind&#39;)

How to implement visual heat map in python

用mask实现:突出显示某些数据

f,(ax1,ax2) = plt.subplots(figsize=(4,6),nrows=2)
x = np.array([[1,2,3],[2,0,1],[-1,-2,0]])
sns.heatmap(x, annot=True, ax=ax1)
sns.heatmap(x, mask=x < 1, ax=ax2, annot=True, annot_kws={"weight": "bold"})   #把小于1的区域覆盖掉

How to implement visual heat map in python

The above is the detailed content of How to implement visual heat map in python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor