Python-Matplotlib drawing those things you don't know

X-axis tick label handling

insert image description here

plt.xticks(rotation=45)

add caption

plt.text() can add text anywhere in the graph, and supports LaTex syntax

text(x, y, s='this is text', fontsize=15)
x: the position of the x-axis
y: the position of the y-axis
s: set the content of the written text fontsize: set the size of the word

import numpy as np
plt.plot(np.random.random(30).cumsum(), color='k', linestyle='dashed', marker='^')
plt.text(18, 10, r'$\mu=100,\ \sigma=15$')
plt.show()

insert image description here

text note

In the process of data visualization, the text in the picture is often used to annotate some features in the picture. Such annotations can be conveniently added using the annotate() method. When using annotate, consider the coordinates of two points: xy(x, y) where the text is annotated and xytext(x, y) where the text is inserted

annotate( s='lxz', xy=(1980, 65.1), xytext=(1970, 77.1),xycoords='data', textcoords='data', color='r', fontsize=20, arrowprops=dict( arrowstyle="->",connectionstyle='arc3',color='r',) )
s: represents the content to be annotated (required parameter)
xy: (actual point) represents the position of the x and y axes (required parameter )
xytext: (the actual position of "comment content") adjust the position of "comment content", if not set, the position of xy will be used
by
default "actual style) If not set, the xycoords setting will be used by default (optional)
color: the color of the comment content fontsize: the font size of the comment content

set arrow

arrowprops=dict(arrowstyle="-", connectionstyle='arc3', color='r',)
arrowstyle: set arrow style connectionstyle: connection style color: arrow color

import numpy as np
plt.plot(np.random.random(30).cumsum(), color='k', linestyle='dashed', marker='^')
plt.annotate('local max', xy=(15, 8), xytext=(8, 12),
            arrowprops=dict(facecolor='r', shrink=0.05))
plt.show()

insert image description here

import matplotlib.pyplot as plt
from matplotlib import style

style.use('ggplot')

fig = plt.figure()
ax1 = plt.subplot2grid((1,1), (0,0))

ax1.plot([1,2,3],[3,7,2],label = 'price')
ax1.plot([3,7,2],[1,2,3],label = 'price2')

font_dict = {
    
    'family':'serif',
             'color':'darkred',
             'size':15}

#我们使用ax1.text添加文本,坐标为(4,4)
#我们使用fontdict参数添加一个数据字典,来使用所用的字体。 
#在我们的字体字典中,我们将字体更改为serif,颜色为『深红色』,然后将字体大小更改为 15。
ax1.text(4, 4,'Text Example(4,4)', fontdict=font_dict)


#用另一种方式进行注解,xytext为比例
ax1.annotate('2nd annotation',(2.9,2.9),
             xytext=(0.4, 0.6), textcoords='axes fraction',
             arrowprops = dict(facecolor='grey',color='grey'))

plt.legend()
plt.show()

insert image description here

Chinese and fonts

method one

Pollution global font setting
plt.rcParams['font.sans-serif'] = ['SimHei'] #Step
1 (replace sans-serif font) plt.rcParams['axes.unicode_minus'] = False #Step
2 (solve coordinates The negative sign of the axis negative number shows the problem)

Method Two

Do not pollute global font settings
plt.ylabel("y-axis", fontproperties="SimSun") # (Song typeface)
plt.title("title", fontproperties="SimHei") # (black body)

font size

plt.rcParams[‘xtick.labelsize’] = 24 plt.rcParams[‘ytick.labelsize’] =
20 plt.rcParams[‘font.size’] = 15

x = range(1,13,1)
y = range(1,13,1)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus']=False
plt.plot(x,y)
plt.title('中文测试')
plt.show()

insert image description here

borders and horizontal lines

fig = plt.figure()
ax1 = plt.subplot2grid((1,1), (0,0))
ax1.plot([1,2,3],[3,7,2],label = 'price', color= 'b')

#左边框设为青色
ax1.spines['left'].set_color('c')

#删除右、上边框
ax1.spines['right'].set_visible(False)
ax1.spines['top'].set_visible(False)

#让左边框变粗
ax1.spines['left'].set_linewidth(5)

#橙色的x轴数值
ax1.tick_params(axis='x', colors='#f06215')

#直接画一条水平线
ax1.axhline(5, color='y', linewidth=3)

plt.show()

insert image description here

stacked chart

Stacked charts are used to show "parts to whole" relationships over time. A stacked chart is basically like a pie chart, only over time.

Let's consider a situation where we have 24 hours in a day and we want to see how we spend our time. We divide our activities into: sleep, eat, work and play.

Let's say we want to track it over a period of 5 days, so our initial data will look like this:

days = [1,2,3,4,5]

sleeping = [7,8,6,11,7]
eating =   [2,3,4,3,2]
working =  [7,8,7,2,2]
playing =  [8,5,7,8,13]

#因此,我们的x轴将包括day变量,即 1, 2, 3, 4 和 5。然后,日期的各个成分保存在它们各自的活动中。

plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','yellow'])

plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.show()

insert image description here
Here we can see, at least in color, how we spend our time. The problem is, we don't know what color is what without looking back at the code. The next problem is that with polygons, we can't actually "label" the data. So anywhere that's not just a line, with a fill like this, or a stacked plot, we can't inherently label specific parts. This shouldn't stop programmers. We can solve this problem:

days = [1,2,3,4,5]

sleeping = [7,8,6,11,7]
eating =   [2,3,4,3,2]
working =  [7,8,7,2,2]
playing =  [8,5,7,8,13]

#我们在这里做的是画一些空行,给予它们符合我们的堆叠图的相同颜色,和正确标签。 
#我们还使它们线宽为 5,使线条在图例中显得较宽。
plt.plot([],[],color='m', label='Sleeping', linewidth=5)
plt.plot([],[],color='c', label='Eating', linewidth=5)
plt.plot([],[],color='r', label='Working', linewidth=5)
plt.plot([],[],color='yellow', label='Playing', linewidth=5)

plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','yellow'])

plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

insert image description here

The pie chart pulls out a

slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']

#slices是切片内容
plt.pie(slices,
        labels=activities,
        colors=cols,
        startangle=90,   #第一条线开始的角度,90度即为竖线
        shadow= True,    
        explode=(0,0.1,0,0),    #一个切片拉出
        autopct='%1.1f%%')   #选择将百分比放置到图表上面

plt.title('Interesting Graph\nCheck it out')
plt.show()

insert image description here
In plt.pie, we need to specify the "slice", which is the relative size of each part. Then, we specify a list of colors for the corresponding slice. Next, we can choose to specify the "start angle" of the graph. This allows you to start drawing anywhere. In our example, we chose a 90-degree angle for the pie chart, which means that the first segment is a vertical bar. Next, we have the option to add a character-sized shadow to the drawing, and then we can even use explode to pull out a slice.

We have four slices in total, so for explode we pass in 0,0,0,0 if we don't want to pull any slices. If we want to pull the first slice, we pass in 0.1,0,0,0.

Finally, we use autopct, choosing to place the percentages on top of the chart.

bubble chart

A kind of scatter diagram, adding the third value s can be understood as ordinary scatter, the drawing is two-dimensional, and the bubble diagram reflects the size of Z

# 泡泡图
np.random.seed(19680801)

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2  # 0 to 15 point radii

plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()

insert image description here

contour line

Both contour and contourf draw three-dimensional contour maps. The difference is that contourf will fill the area between contour lines.

x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
plt.contour(x, y, z) # contourf
plt.show()

insert image description here

import matplotlib.pyplot as plt
import numpy as np

# 定义等高线高度函数
def f(x, y):
    return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(- x ** 2 - y ** 2)

# 数据数目
n = 256
# 定义x, y
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)

# 生成网格数据
X, Y = np.meshgrid(x, y)


# 填充等高线的颜色, 8是等高线分为几部分
plt.contourf(X, Y, f(X, Y), 8, alpha = 0.75, cmap = plt.cm.hot)
# 绘制等高线
C = plt.contour(X, Y, f(X, Y), 8, colors = 'black', linewidth = 0.5)
# 绘制等高线数据
plt.clabel(C, inline = True, fontsize = 10)

# 去除坐标轴
plt.xticks(())
plt.yticks(())
plt.show()

insert image description here

radar chart

# 导入第三方模块
import numpy as np
import matplotlib.pyplot as plt

# 中文和负号的正常显示
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

# ------------------------------------------------
# 数据处理和准备
values = [98, 45, 124, 83, 90, 94] # 数值
labels = ['语文', '英语', '数学', '物理', '化学', '生物']  # 标签
# 设置雷达图的角度,用于平分切开一个圆面
angles = np.linspace(0, 2 * np.pi, len(values), endpoint=False)  # 角度
'''
—— 拼接数组:
# 注意:数组之间形状要一致才可以拼接
np.concatenate((a, b), axis=0) 一维数组
np.concatenate((c, d), axis=1) 二维数组
'''
# 为了使雷达图一圈封闭起来,需要下面的步骤, 首尾相连
values = np.concatenate((values,[values[0]]))  
angles = np.concatenate((angles,[angles[0]]))  
print('\n>>>', values, '\n>>>', angles)


# --------------------------------------------------
# 绘图
fig = plt.figure()

''' 雷达图的核心 '''
# polar=True 这里一定要设置为极坐标格式
ax = fig.add_subplot(111, polar=True)
ax.plot(angles, values, marker='o', color='r', linewidth=2)  # 绘制折线图
ax.fill(angles, values, color='b', alpha=0.25)  # 填充蓝色颜色
ax.set_thetagrids(angles * 180/np.pi, labels)  # 添加每个特征的标签
'''
注意:
ax.plot(x=angles, y=values, marker='o', linewidth=2)
加上 x, y 显示不出线的标记
'''

# -------------------------------------------------
# 其他设置
ax.set_ylim(0,150)  # 设置雷达图的范围
plt.title('单个学生成绩展示')  # 添加标题
ax.grid(True)  # 添加网格线
plt.show()

insert image description here

shared axes

Share an x-axis coordinate, and use two scales on the left and right sides of the y-axis to identify

Axes.twinx(), Axes.twiny() are used to generate axis instances to share x or y coordinate axes
matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False)
nrows,ncols: Used to determine the number of rows and columns for drawing subgraphs
sharex, sharey: Used to determine whether to share the axis scale. When set to True or all, the parameter scale will be shared. When set to False or None, each subdrawing will be It has its own independent scale. When it is set to row or col, it will share the x and y axis scales of the row and column. When sharex='col', only the x scale label of the bottom axes of the column will be created

# 共享x坐标轴
# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

insert image description here

Three-dimensional map

The mpl_toolkits.mplot3d module provides three-dimensional drawing functions based on matplotlib. Because it uses the two-dimensional drawing function of matplotlib to realize the drawing work of three-dimensional graphics, the drawing speed is limited, and it is not suitable for three-dimensional drawing of large-scale data. If you need more complex 3D data visualization capabilities, you can use Mayavi.

1 Create 3D graphic objects

fig = plt.figure() # Create image object
ax = Axes3D(fig) # Create 3D multi-axis object

2 Draw the surface

Axes3D.plot_surface(X, Y, Z, *args, **kwargs)

3. Set the axis range

Set the range of x, y, z axis [a, b]
ax.set_xlim(a, b)
ax.set_ylim(a, b)
ax.set_zlim(a,b)

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(8, 6))
ax = Axes3D(fig)
delta = 0.125
# 生成代表X轴数据的列表
x = np.arange(-3.0, 3.0, delta)
# 生成代表Y轴数据的列表
y = np.arange(-2.0, 2.0, delta)
# 对x、y数据执行网格化
X, Y = np.meshgrid(x, y)
Z1 = np.exp(-X**2 - Y**2)
Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
# 计算Z轴数据(高度数据)
Z = (Z1 - Z2) * 2
# 绘制3D图形
ax.plot_surface(X, Y, Z,
    rstride=1,  # rstride(row)指定行的跨度
    cstride=1,  # cstride(column)指定列的跨度
    cmap=plt.get_cmap('rainbow'))  # 设置颜色映射
# 设置Z轴范围
ax.set_zlim(-2, 2)
# 设置标题
plt.title("3D")
plt.show()

insert image description here
Projection Mode
The projection mode determines the way points are converted from data coordinates to screen coordinates. The name of the currently valid projection mode can be obtained through the following statement:

from matplotlib import projections
projections.get_projection_names()

The '3d' projection mode appears in this list only after the mplot3d module has been loaded. 'aitoff', 'hammer', 'lamberf', 'mollweide', etc. are all map projections, 'polar' is polar coordinate projection, and 'rectilinear' is the default rectilinear projection mode.

import numpy as np
import mpl_toolkits.mplot3d 
import matplotlib.pyplot as plt

x, y = np.mgrid[-2:2:20j, -2:2:20j] 
z = x * np.exp( - x**2 - y**2)
ax = plt.subplot(111, projection='3d') 
ax.plot_surface(x, y, z, rstride=2, cstride=1, cmap = plt.cm.Blues_r) 
ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
plt.show()

insert image description here

from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm)
plt.show()

insert image description here

Guess you like

Origin blog.csdn.net/qq_47326711/article/details/127459275