Public account: You and the cabin by: Peter Editor: Peter
Hello, I’m Peter
There have been a number of recent updates on Plotly mapping. Today’s article is based on the official website and practical cases to explain how to draw thermal maps under different requirements.
There are 3 ways to draw heat maps in Plotly: Heatmap, imshow, and Figure_factory (Plotly’s graphic factory function)
Official website study address:
- Plotly.com/python/heat…
- Plotly.com/python/imsh…
- Plotly.com/python/anno…
directory
The overall contents of this article:
Serialized article by Plotly
For a few Plotly updates, check out:
Import libraries
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 # Graphics Factory
from plotly.subplots import make_subplots # Draw a subgraph
Copy the code
Display imshow based on PX
The imshow in Plotly is mainly used to display graphic data, but can also be used to display thermal maps:
Display RGB graph data
# Data section
rgb = np.array([[[105.0.0], [0.255.0], [0.0.55]],
[[0.250.0], [0.0.205], [255.0.0]]],
dtype=np.uint8)
# call px
fig = px.imshow(rgb)
fig.show()
Copy the code
Based on nested lists
fig = px.imshow([[1.20.30],
[20.1.60]])
fig.show()
Copy the code
Data based on a two-dimensional array
1. Display color bar and color
data = np.arange(20).reshape(4.5) How to use Numpy to generate data
fig = px.imshow(data)
fig.show()
Copy the code
2, do not display color bar + gray
data = np.arange(20).reshape(4.5)
fig = px.imshow(data,binary_string=True) # parameter Settings
fig.show()
Copy the code
3, display gray + color bar
data = np.arange(20).reshape(4.5)
fig = px.imshow(data,color_continuous_scale="gray") # parameter Settings
fig.show()
Copy the code
Based on the data in the graphics file
1. Basic graphics
Import data from skimage
from skimage import data
# import specified image data
img = data.astronaut()
fig = px.imshow(img,
binary_format="jpeg",
binary_compression_level=0)
fig.show()
Copy the code
2, do not display the axis scale
Import data from skimage
from skimage import data
# import specified image data
img = data.astronaut()
fig = px.imshow(img,
binary_format="jpeg",
binary_compression_level=0)
# Do not display color range and axis scale
fig.update_layout(coloraxis_showscale=False)
fig.update_xaxes(showticklabels=False)
fig.update_yaxes(showticklabels=False)
fig.show()
Copy the code
Custom axis calibration value
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, # incoming data
Axis label Settings
labels=dict(x="Week", y="Time of Day", color="Productivity"),
# Axis calibration Settings
x=['Monday'.'Tuesday'.'Wednesday'.'Thursday'.'Friday'],
y=['early'.'in'.'late'])# Axis position adjustment
fig.update_xaxes(side="top")
fig.show()
Copy the code
Show imShow based on go
The Graph_objects method supports two methods to draw images:
- Go. Image: Supports only multi-channel Image data
- Go.Heatmap: Supports image data in a single channel
Based on the go.Image method
import plotly.graph_objects as go
# 2*3*3 list
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()
Copy the code
Based on the go. HeatMap method
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()
Copy the code
Missing value handling
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)) # Missing value processing parameter
fig.show()
Copy the code
Based on the graph factory figure_Factory
An important function of figure_factory is to draw thermal maps with labels. We can see that all the above graphics are unmarked
Basic shapes
How to draw basic graphics to be marked based on graphic foreman:
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()
Copy the code
Custom colors
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]]
# Add parameter: colorScale
fig = ff.create_annotated_heatmap(z,colorscale='Viridis')
fig.show()
Copy the code
How to set different colors:
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.]]
This is more flexible by using nested lists to specify gradients for colors
colorscale = [[0.0.'green'], [0.5.'blue'], [1.'yellow']]
# specify the font color
font_colors = ['white'.'red']
Pass in the font and color parameters
fig = ff.create_annotated_heatmap(z, colorscale=colorscale, font_colors=font_colors)
fig.show()
Copy the code
Custom XY axis
import plotly.figure_factory as ff
# Display data
z = [[101.131.95],
[112.74.146]]
# Two axes, optionally specified
x = ["Chinese"."Mathematics"."English"]
y = ["Xiao Ming"."Little red"]
The data to be annotated is generally the same as z
z_text = [[101.131.95],
[112.74.146]]
fig = ff.create_annotated_heatmap(
z,
x=x,
y=y,
annotation_text=z_text, # Annotate text content
colorscale='Viridis')
fig.show()
Copy the code
Set font size
Sometimes we change the font size in standard text:
import plotly.figure_factory as ff
# Display data
z = [[101.131.95],
[112.74.146]]
# Two axes, optionally specified
x = ["Chinese"."Mathematics"."English"]
y = ["Xiao Ming"."Little red"]
The data to be annotated is generally the same as z
z_text = [[101.131.95],
[112.74.146]]
fig = ff.create_annotated_heatmap(
z,
x=x,
y=y,
annotation_text=z_text, # Annotate text content
colorscale='Viridis')
# font size Settings
for i in range(len(fig.layout.annotations)):
fig.layout.annotations[i].font.size=20
fig.show()
Copy the code
Actual combat 1: Thermal map of correlation coefficient
Using stock data
Plotly_express built-in stock data; The correlation coefficient between two companies is solved by correlation coefficient function CORr function
stock = px.data.stocks()
stock.head()
Copy the code
A piece of data about a stock built into Plotly:
The correlation coefficient
Generate the correlation coefficient matrix while preserving two decimal places:
Coordinate axes and plot data
Generate axes and data to be plotted:
drawing
import plotly.figure_factory as ff
# Display data
z = data1
# Two axes, optionally specified
x = index
y = columns
# Display text content
z_text = data1
fig = ff.create_annotated_heatmap(
z,
x=x,
y=y,
annotation_text=z_text, # Annotate text content
colorscale='Viridis',
showscale=True
)
# font size Settings
for i in range(len(fig.layout.annotations)):
fig.layout.annotations[i].font.size=12
fig.show()
Copy the code
Case 2: Draw a thermal map of any coordinate axis
This case is a solution to a problem I once encountered, that is, how to solve the problem when there are two types of value and string in our coordinate axis.
Similar cases on official website
Both axes specify string data
import plotly.figure_factory as ff
z = [[101.131.95],
[112.74.146]]
# Important: both are strings
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, # Annotate text content
colorscale='Viridis')
fig.show()
Copy the code
Here is a diagram:
Change the axis data
In the data of the coordinate axes, use both numbers and strings:
There is no picture: what is the problem?
How to solve it? Two methods are introduced:
Method 1: Set parameters
import plotly.figure_factory as ff
z = [[101.131.95],
[112.74.146]]
# 1. Set the axis data and unify the data format
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')
# Solutions
# Actual axis
xticks=[1.'Team B'.'Team C']
yticks=[1.'Game One']
# Change the coordinate axes: replace x with xticks, y is similar
fig.update_xaxes(tickvals=x, ticktext=xticks)
fig.update_yaxes(tickvals=y, ticktext=yticks)
fig.show()
Copy the code
Method 2: Customize the function
import plotly.figure_factory as ff
z = [[101.131.95],
[112.74.146]]
x = [1.'Team B'.'Team C']
y = [1.'Game One']
# Data to display
z_text = z
# Key function: Modify the axis
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()
Copy the code
Perfect solution!