如何在Python中更改 seaborn 热图图的颜色条大小?
先决条件: Seaborn
颜色条是用于解释热图数据的矩形色标。默认情况下,它与热图大小相同,但可以使用 heatmap()函数的 cbar_kws 参数更改其大小。此参数接受字典类型值并更改颜色条的大小,其收缩参数需要相应地。默认情况下,它是 1,这使得颜色条与热图大小相同。要使颜色条变小,应为收缩指定一个小于 1 的值,而要增加其大小,应为其指定一个大于 1 的值。
heatmap() 的语法:
Syntax: seaborn.heatmap(data, *, vmin=None, vmax=None, cmap=None, center=None, annot_kws=None, linewidths=0, linecolor=’white’, cbar=True, **kwargs)
Important Parameters:
- data: 2D dataset that can be coerced into an ndarray.
- vmin, vmax: Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments.
- cmap: The mapping from data values to color space.
- center: The value at which to center the colormap when plotting divergent data.
- annot: If True, write the data value in each cell.
- fmt: String formatting code to use when adding annotations.
- linewidths: Width of the lines that will divide each cell.
- linecolor: Color of the lines that will divide each cell.
- cbar: Whether to draw a colorbar.
All the parameters except data are optional.
Returns: An object of type matplotlib.axes._subplots.AxesSubplot
方法
- 导入模块
- 加载或创建数据
- 使用适当的值创建热图,在此函数本身内,使用收缩及其所需值设置 cbar_kws。
- 显示图
下面给出了使用这种方法的实现:
使用中的数据库:畅销书
示例 1:减小颜色条的大小
Python3
# import modules
import matplotlib.pyplot as mp
import pandas as pd
import seaborn as sb
# load data
data = pd.read_csv("bestsellers.csv")
# plotting heatmap
sb.heatmap(data.corr(), annot=None, cbar_kws={'shrink': 0.6})
# displaying heatmap
mp.show()
Python3
# import modules
import matplotlib.pyplot as mp
import pandas as pd
import seaborn as sb
# load data
data = pd.read_csv("bestsellers.csv")
# plotting heatmap
sb.heatmap(data.corr(), annot=None, cbar_kws={'shrink': 1.3})
# displaying heatmap
mp.show()
输出:
示例 2:增加颜色条的大小
蟒蛇3
# import modules
import matplotlib.pyplot as mp
import pandas as pd
import seaborn as sb
# load data
data = pd.read_csv("bestsellers.csv")
# plotting heatmap
sb.heatmap(data.corr(), annot=None, cbar_kws={'shrink': 1.3})
# displaying heatmap
mp.show()
输出: