Fork me on GitHub

可视化神器Plotly绘制热力图

Plotly制作热力图

之前更新了很多关于Plotly绘图的文章。今天带来的文章是基于官网和实际案例来讲解如何绘制不同需求下的热力图。

Plotly中绘制热力图有3种方式:heatmap、imshow和figure_factory(Plotly的图形工厂函数)

官网学习地址:

目录

本文的整体目录:

Plotly连载文章

几篇Plotly更新的文章,请参考:

导入库

1
2
3
4
5
6
7
import pandas as pd
import numpy as np

import plotly_express as px
import plotly.graph_objects as go
import plotly.figure_factory as ff # 图形工厂
from plotly.subplots import make_subplots # 绘制子图

基于px展示imshow

Plotly中的imshow主要是用来展示图像数据,当然也可以用来显示热力图:

展示RGB图形数据

1
2
3
4
5
6
7
8
# 数据部分
rgb = np.array([[[105, 0, 0], [0, 255, 0], [0, 0, 55]],
[[0, 250, 0], [0, 0, 205], [255, 0, 0]]],
dtype=np.uint8)

# 调用px
fig = px.imshow(rgb)
fig.show()

基于嵌套列表

1
2
3
4
fig = px.imshow([[1, 20, 30],
[20, 1, 60]])

fig.show()

基于二维数组的数据

1、显示颜色棒及颜色

1
2
3
data = np.arange(20).reshape(4,5) # 如何使用Numpy生成数据
fig = px.imshow(data)
fig.show()

2、不显示颜色棒+灰色

1
2
3
data = np.arange(20).reshape(4,5)
fig = px.imshow(data,binary_string=True) # 参数设置
fig.show()

3、显示灰色+颜色棒

1
2
3
data = np.arange(20).reshape(4,5)
fig = px.imshow(data,color_continuous_scale="gray") # 参数设置
fig.show()

基于图形文件中的数据

1、基础图形

1
2
3
4
5
6
7
8
9
10
# 从skimage中导入数据
from skimage import data

# 导入指定图像数据
img = data.astronaut()

fig = px.imshow(img,
binary_format="jpeg",
binary_compression_level=0)
fig.show()

2、不显示坐标轴刻度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 从skimage中导入数据
from skimage import data

# 导入指定图像数据
img = data.astronaut()

fig = px.imshow(img,
binary_format="jpeg",
binary_compression_level=0)

# 不显示颜色范围和轴刻度
fig.update_layout(coloraxis_showscale=False)
fig.update_xaxes(showticklabels=False)
fig.update_yaxes(showticklabels=False)

fig.show()

自定义轴刻度值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import plotly.express as px

data=[[1, 25, 30, 50, 100],
[20, 10, 60, 80, 30],
[13, 60, 31, 5, 20]]

fig = px.imshow(
data, # 传入数据
# 轴标签设置
labels=dict(x="Week", y="Time of Day", color="Productivity"),
# 轴刻度设置
x=['星期一', '星期二', '星期三', '星期四', '星期五'],
y=['早', '中', '晚']
)

# 轴位置调整
fig.update_xaxes(side="top")

fig.show()

基于go展示imshow

graph_objects方法支持两种方法来绘制图像绘制:

  • go.Image:仅支持多通道的图像数据
  • go.Heatmap:支持单通道的图像数据

基于go.Image方法

1
2
3
4
5
6
7
8
9
import plotly.graph_objects as go

# 2*3*3的列表
rgb = [[[200, 0, 0], [0, 200, 0], [0, 0, 255]],
[[0, 255, 0], [0, 0, 205], [255, 0, 0]]]

fig = go.Figure(go.Image(z=rgb))

fig.show()

基于go.heatMap方法

1
2
3
4
5
6
7
8
9
10
import plotly.graph_objects as go

fig = go.Figure(data=go.Heatmap(
z=[[10, 20, 30],
[20, 1, 60],
[30, 60, 10]]))

fig.update_layout(width=800,height=500)

fig.show()

缺失值处理

1
2
3
4
5
6
7
8
import plotly.graph_objects as go

fig = go.Figure(data=go.Heatmap(
z=[[1, None, 30, 50, 1], [20, 1, 60, np.nan, 30], [30, 60, 1, -10, 20]],
x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
y=['Morning', 'Afternoon', 'Evening'],
hoverongaps = False)) # 缺失值处理参数
fig.show()

基于图形工厂 figure_factory

figure_factory图形工厂一个重要的作用就是绘制带有标注的热力图。我们可以看到上面的各种图形都是没有标注的

基础图形

基于图形工长如何绘制基本待标注的基本图形:

1
2
3
4
5
6
7
8
9
import plotly.figure_factory as ff

z = [[1.1, .3, .5, .7, .9],
[1, .8, .6, .4, .2],
[.2, 0, .5, .7, .9],
[.9, .8, .4, .2, 0]]

fig = ff.create_annotated_heatmap(z)
fig.show()

自定义颜色

1
2
3
4
5
6
7
8
9
10
11
import plotly.figure_factory as ff

z = [[1.1, .3, .5, .7, .9],
[1, .8, .6, .4, .2],
[.2, 0, .5, .7, .9],
[.9, .8, .4, .2, 0]]

# 添加参数:colorscale
fig = ff.create_annotated_heatmap(z,colorscale='Viridis')

fig.show()

如何设置不同的颜色:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import plotly.figure_factory as ff

z = [[.1, .3, .5, .7],
[1.0, .8, .6, .4],
[.6, .4, .2, 0.0],
[.9, .7, .5, .3]]

# 这种写法通过嵌套列表来指定颜色的渐变,更加灵活
colorscale = [[0.0, 'green'],[0.5, 'blue'],[1, 'yellow']]

# 指定字体的颜色
font_colors = ['white', 'red']
# 传入字体和颜色参数
fig = ff.create_annotated_heatmap(z, colorscale=colorscale, font_colors=font_colors)
fig.show()

自定义XY轴

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import plotly.figure_factory as ff

# 显示的数据
z = [[101,131,95],
[112,74,146]]

# 两个轴,可以任意指定
x = ["语文","数学","英语"]
y = ["小明","小红"]

# 待注释的数据,一般和z相同
z_text = [[101,131,95],
[112,74,146]]

fig = ff.create_annotated_heatmap(
z,
x=x,
y=y,
annotation_text=z_text, # 标注文本内容
colorscale='Viridis')

fig.show()

设置字体大小

有时候我们更改标准文本中字体的大小:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import plotly.figure_factory as ff

# 显示的数据
z = [[101,131,95],
[112,74,146]]

# 两个轴,可以任意指定
x = ["语文","数学","英语"]
y = ["小明","小红"]

# 待注释的数据,一般和z相同
z_text = [[101,131,95],
[112,74,146]]

fig = ff.create_annotated_heatmap(
z,
x=x,
y=y,
annotation_text=z_text, # 标注文本内容
colorscale='Viridis')

# 字体大小设置
for i in range(len(fig.layout.annotations)):
fig.layout.annotations[i].font.size=20

fig.show()

实战1:相关系数热力图

使用股票数据

采用的plotly_express内置的股票数据;通过相关系数函数corr函数求解出两两公司之间的相关系数

1
2
stock = px.data.stocks()
stock.head()

Plotly中内置的一份关于股票的数据:

相关系数

生成相关系数矩阵,同时保留两位小数:

坐标轴和绘图数据

生成坐标轴和待绘图的数据:

绘图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import plotly.figure_factory as ff

# 显示的数据
z = data1

# 两个轴,可以任意指定
x = index
y = columns
# 显示的文本内容
z_text = data1

fig = ff.create_annotated_heatmap(
z,
x=x,
y=y,
annotation_text=z_text, # 标注文本内容
colorscale='Viridis',
showscale=True
)

# 字体大小设置
for i in range(len(fig.layout.annotations)):
fig.layout.annotations[i].font.size=12

fig.show()

案例2:绘制任意坐标轴热力图

这个案例是自己曾经遇到的一个问题的解决过程,就是当我们的坐标轴中出现了数值和字符串两种类型如何解决。

官网类似案例

两个轴指定的都是字符串类型的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import plotly.figure_factory as ff

z = [[101,131,95],
[112,74,146]]

# 重点:都是字符串类型
x = ['Team A', 'Team B', 'Team C']
y = ['Game Two', 'Game One']

z_text = [[101,131,95],
[112,74,146]]

fig = ff.create_annotated_heatmap(
z,
x=x,
y=y,
annotation_text=z_text, # 标注文本内容
colorscale='Viridis')

fig.show()

下面是可以出图的:

改变坐标轴数据

在坐标轴的数据中,同时使用数值和字符串:

这样子就不能出图:问题到底出在哪里呢?

如何解决?介绍两种方法:

方法1:通过参数设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import plotly.figure_factory as ff

z = [[101,131,95],
[112,74,146]]

# 1、设置坐标轴数据,统一用数据格式
x = list(range(0,3))
y = list(range(0,2))

z_text = [[101,131,95],
[112,74,146]]

fig = ff.create_annotated_heatmap(
z,
x=x,
y=y,
annotation_text=z_text,
colorscale='Viridis')

# 解决方法
# 实际坐标轴
xticks=[1, 'Team B', 'Team C']
yticks=[1, 'Game One']

# 修改坐标轴:将x用xticks来代替,y轴类似
fig.update_xaxes(tickvals=x, ticktext=xticks)
fig.update_yaxes(tickvals=y, ticktext=yticks)
fig.show()

方法2:自定义函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import plotly.figure_factory as ff

z = [[101,131,95],
[112,74,146]]

x = [1, 'Team B', 'Team C']
y = [1, 'Game One']

# 待显示的数据
z_text = z

# 关键函数:修改坐标轴
def hm_axis(l):
return [f"{chr(0)+str(i)+chr(0)}" for i in l]

fig = ff.create_annotated_heatmap(
z,
x=hm_axis(x),
y=hm_axis(y),
annotation_text=z_text,
colorscale='Viridis')
fig.show()

完美解决!

本文标题:可视化神器Plotly绘制热力图

发布时间:2021年11月25日 - 14:11

原始链接:http://www.renpeter.cn/2021/11/25/%E5%8F%AF%E8%A7%86%E5%8C%96%E7%A5%9E%E5%99%A8Plotly%E7%BB%98%E5%88%B6%E7%83%AD%E5%8A%9B%E5%9B%BE.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea