当前位置:   article > 正文

matplotlib画图示例_matplotlib boxplot 和 plot 在一张画布上

matplotlib boxplot 和 plot 在一张画布上

1.使用matplotlib.pyplot将几个子图画在一幅图中

1.1 matplotlib.pyplot(plt)程序

各二维子图的值均为np.random.random产生的随机数

import numpy as np
import matplotlib.pyplot as plt
import os 
fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(8, 8))
  
for i in range(2):
    for j in range(2):    
        axs[i, j].scatter(np.random.random((100)), np.random.random((100)),c=np.random.randint(1,4,(100)),s=1)
        axs[i, j].set_title(str(i*2+j))
        
plt.tight_layout()        
plt.savefig( "D:\\"+str(i*2+j))
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

1.2 结果

在D:\下生成图片3.png,其由4个子图组成,sub_title分别为0~3。
在这里插入图片描述

2.设置plt图中x,y坐标单位长度相同

plt.gca().set_aspect(‘equal’)

示例:
在这里插入图片描述

3.不显示坐标轴、刻度、边框

import  matplotlib.pyplot  as plt
from matplotlib.ticker import NullLocator
import numpy as np

x=np.random.random((1000,2))
y=np.random.randint(0,255,(1000,))
plt.scatter(x[:,0],x[:,1],s=1,c=y)

plt.axis("off")
plt.gca().xaxis.set_major_locator(NullLocator())
plt.gca().yaxis.set_major_locator(NullLocator())
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

效果如下:
在这里插入图片描述

4.一定时间后自动关闭plot画面

plt.ion()
plt.plot(***)
# plt.show()
plt.savefig(f'{pic_name}.jpg')
plt.pause(2)       # 显示秒数
plt.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5.matplotlib画3D图

三维图matlab是真心好用,即使用surf()。

而目前matplotlib相对没有那么简单。

下面这个例子以z为x,y平方和的均值,画出对应的三维图。

import numpy as np
import matplotlib.pyplot as plt

def f(x, y):
 return np.sqrt(x ** 2 + y ** 2)
x = np.linspace(-6,6,30)
y = np.linspace(-6,6,30)
X, Y = np.meshgrid(x, y)
Z = f(X,Y)
 
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.view_init(20, 35)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

在这里插入图片描述
图还是不错的,就是视角根据需要调整。

6. 显示legend

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets

np.random.seed(123)
n_samples = 200
noisy_moons = datasets.make_moons(n_samples=n_samples, noise=0.05)
features = noisy_moons[0]
labels = noisy_moons[1]

c_s = ['r', 'b', 'darkgrey']

mk = ["^", "o"]
markers = np.array([mk[item] for item in labels])
colors = np.array([c_s[item] for item in labels])

plt.scatter(features[labels == 1][:, 0], features[labels == 1]
            [:, 1], c=colors[labels == 1], marker="o", label="labeled 0")
plt.scatter(features[labels == 0][:, 0], features[labels == 0]
            [:, 1], c=colors[labels == 0], marker="o", label="labeled 1")

plt.legend(scatterpoints=1, frameon=False,
           labelspacing=1, loc='lower left')
plt.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

在这里插入图片描述

7. 画boxplot

设data维度为num*6,画出6个box图:

fig, ax = plt.subplots()
labels=[item.split('.')[0] for item in file_names]
VP = ax.boxplot(data, positions=[2, 4, 6, 8, 10, 12],
                patch_artist=True,
                vert=True,
                showmeans=True, showfliers=True,
                medianprops={"color": "red", "linewidth": 0.5}, 
                labels=labels
                )
for box, c in zip(VP['boxes'], colors):
    box.set(facecolor=c)
plt.show() 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

在这里插入图片描述

8.常用资料

8.1 Matplotlib rcParams

8.1.1 画图中设置title的中文支持

在使用Matplotlib.pyplot画图过程中,有时需要设置中文标题,如:
axs[0].set_title(u"标题1")
这时候标题的位置会默认显示“□□□”。
为了将中文字体显示出来,需要进行一些设置:

plt.rcParams['font.sans-serif'] = ['KaiTi']
plt.rcParams['font.serif'] = ['KaiTi']
  • 1
  • 2

这里的’KaiTi’,即设置为楷体字体。参考CSS 中文字体的英文名称1

华文细黑:STHeiti Light [STXihei]
华文黑体:STHeiti
华文楷体:STKaiti
华文宋体:STSong
华文仿宋:STFangsong
俪黑 Pro:LiHei Pro Medium
俪宋 Pro:LiSong Pro Light
标楷体:BiauKai
苹果俪中黑:Apple LiGothic Medium
苹果俪细宋:Apple LiSung Light

Windows的一些:

新细明体:PMingLiU
细明体:MingLiU
标楷体:DFKai-SB
黑体:SimHei
宋体:SimSun
新宋体:NSimSun
仿宋:FangSong
楷体:KaiTi
仿宋_GB2312:FangSong_GB2312
楷体_GB2312:KaiTi_GB2312
微软正黑体:Microsoft JhengHei
微软雅黑体:Microsoft YaHei

装Office会生出来的一些:

隶书:LiSu
幼圆:YouYuan
华文细黑:STXihei
华文楷体:STKaiti
华文宋体:STSong
华文中宋:STZhongsong
华文仿宋:STFangsong
方正舒体:FZShuTi
方正姚体:FZYaoti
华文彩云:STCaiyun
华文琥珀:STHupo
华文隶书:STLiti
华文行楷:STXingkai
华文新魏:STXinwei


如果显示中文标题后,数字中“-“号无法显示,可以设置:
```python
matplotlib.rcParams['axes.unicode_minus'] =False
  • 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
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

8.1.2 font.family

Matplotlib 的font具有以下五个属性:

  • ‘serif’ (e.g., Times),
  • ‘sans-serif’ (e.g., Helvetica),
  • ‘cursive’ (e.g., Zapf-Chancery),
  • ‘fantasy’ (e.g., Western), and
  • ‘monospace’ (e.g., Courier).

那么分别代表什么意思呢,可参考2

※Serif:在字的笔划开始及结束的地方有额外的装饰,而且笔划的粗细会因直横的不同而有不同。

※Sans Serif则没有这些额外的装饰。

如:
在这里插入图片描述
※Monospace:等宽字体
※Cursive书写体:相当于印刷学中的手写体。中文的华文行草就是这样的一个字体。

8.2 matplotlib.markers

此内容见matplotlib.markers
在这里插入图片描述

8.2 .1 画出空心marker

设置edgecolors,同时将color设为空,即为空心marker:

markers=["o","s","D","^"]
for i in range(4):
    plt.scatter(X_reduced[colrs==i, 0], X_reduced[colrs==i, 1],
                 marker=markers[i],s=80, color='',edgecolors='g')
  • 1
  • 2
  • 3
  • 4

在这里插入图片描述

8.3 matplotlib颜色大全3

在这里插入图片描述

9.散点图交互式展示

9.1 阻塞

目前是通过以下语句实现交互式显示图片的阻塞(关闭之后才能显示下一张):

plt.show(block=True)
  • 1

如:

for i in range(4):
    plt.figure()
    ar=np.random.randint(0,10,(10))
    plt.plot(ar)
    plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5

其效果是弹出了四张图片。

添加block=True之后,手动关闭显示下一张,可以逐次查看效果。

9.2 散点图交互式展示

可以参考github matplotlib交互式展示数据.ipynb或者csdn blogmatplotlib键盘鼠标事件(tcy)

其原理在于获取触发事件,然后进行响应。

事件包括:

'button_press_event'

'button_release_event'

'draw_event'

'key_press_event'

'key_release_event'

'motion_notify_event'

'pick_event'

'resize_event'

'scroll_event'

'figure_enter_event',

'figure_leave_event',

'axes_enter_event',

'axes_leave_event'

'close_event'.
  • 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

9.2.1 鼠标按键或者滑动

import matplotlib
from matplotlib import pyplot as plt
import numpy as np
matplotlib.use('TkAgg')

fig,ax = plt.subplots()
x=list(range(1,10))
y=[2*v for v in x]
sc=ax.scatter(x,y, ) # 5 points tolerance

def onclick(event):
    cont = False
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
    if cont:
        print(cont, ind)        
        pos = sc.get_offsets()[ind["ind"][0]]
        annot.xy = sc.get_offsets()[ind["ind"][0]]
        text = f"{ind['ind'][0]}"
        annot.set_text(text)
        annot.get_bbox_patch().set_facecolor('r')
        annot.get_bbox_patch().set_alpha(0.4)
        annot.set_visible(True)
        fig.canvas.draw_idle()
        cont = False
    else:
        if vis: 
            annot.set_visible(False)
            fig.canvas.draw_idle()
annot = ax.annotate(
    "", xy=(
        0, 0), xytext=(
        20, 20), textcoords="offset points", bbox=dict(
        boxstyle="round", fc="w"), arrowprops=dict(
        arrowstyle="->"))
annot.set_visible(False)
fig.canvas.mpl_connect('button_press_event', onclick)  # motion_notify_event
plt.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
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

button_press_event 或者motion_notify_event事件,都可以。
效果如下:
在这里插入图片描述

  • 可以通过事件设置两张三维子图实现同步旋转:

可以定义一个'button_press_event'事件,在其触发函数里实现子图同步旋转。

def click_trigger(self, event):
    if event.inaxes == ax0:
        ax1.view_init(ax0.elev, ax0.azim)    
    elif event.inaxes == ax1:
        ax0.view_init(ax1.elev, ax1.azim)            
  • 1
  • 2
  • 3
  • 4
  • 5

9.2.2 使用ginput()方法

除此之外,还可以使用ginput()

import sys
import keyboard

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x=range(1,10)
y=[2*v for v in x]
plt.plot(x, y)
while(1):
    if keyboard.is_pressed("q"):# q键退出
        plt.close()
        sys.exit()
    pos=plt.ginput()
    print(pos)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

9.3 三维散点图通过事件触发获得错误数据index的解决方法

通过鼠标捕获事件,显示散点图中序号时,发现具体到某一个数据点,转动散点图,序号会变化,而且显示出的数值和坐标轴也对不上。

在这里插入图片描述
想了下,散点图中实际scatter的点的序号,应该和原矩阵中各数据的序号不一致。 但具体是怎么排布的,也没有再深入分析。

参考 9,对代码进行了修改:

cont, ind = sc1.contains(event)
ind = ind["ind"][0]# 散点图中的序号

pos = sc.get_offsets()[ind]# 散点图中位置
annot.xy = pos

ind = sc._z_markers_idx[ind]# 矩阵中的序号
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

通过这个方法就可以获取矩阵中的序号和数据了。

10.画stem图

stem图在多维时序信号的比较中,看起来非常直观。

使用时可以用plt.stem。如果有多个子图用ax.stem。其基本用法是一样的。

这里以ax.stem为例:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(nrows = 2, ncols = 1, igsize = (8, 4))
cycles=10
x = np.arange(cycles)
y = np.random.randint(0,cycles,(2,cycles,4))

attr = ["A", "B", "C", "D"]
markers = ["ro", "bs", "gD", "y^"]

for i in range(2):
    for j in range(4):
        ax[i].stem(x, y[i,:, j], markerfmt=markers[j], linefmt='k--', label=attr[j],basefmt='c--')
        ax[i].set_xticks(np.arange(0, cycles, 1))
        ax[i].legend(loc='upper left', ncol=4)
plt.show(block=True)
plt.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

其中,使用了:

set_xticks 设置刻度
legend     设置图例

markerfmt  设置标记的形状和颜色
linefmt    设置stem的线型、颜色
basefmt    设置底部线条线型、颜色
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

线型标识如下:
在这里插入图片描述
颜色设置可参考 matplotlib colors
在这里插入图片描述

效果如下:
在这里插入图片描述

11.一维高斯分布

import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm

mu = np.array(100)
std = np.array(25)
gaussian = norm(mu, std)
samples = gaussian.rvs(size=10000)

x = np.linspace(25, 175, 100)
y = gaussian.pdf(x)
plt.title(f"mu={mu}, std={std}")
plt.plot(x, y)

plt.hist(samples,bins=30, density=True,)

plt.show(block=True)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

在这里插入图片描述

12.一维插值

import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
x = np.arange(0, 10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x,y, kind="cubic")

xnew = np.arange(2, 9)
ynew = f(xnew)   # use interpol'ation function returned by `interp1d`
plt.plot(x, y, '-', xnew, ynew, '*')
plt.grid(True)
plt.show(block=True)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

在这里插入图片描述

13.带密度的子图+colormap

import matplotlib.pyplot as plt
import numpy as np
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.ticker import MultipleLocator
from scipy.stats import gaussian_kde

data=np.random.random((1000,12))

plt.subplots(nrows=3, ncols=2, figsize=(8, 8))
plot_index=[1,3,5,2,4,6]

for i in range(3):
    for j in range(2):
        ind = i+j*3

        z = gaussian_kde(data[:, i+j*3].T)(data[:, i+1+j*3].T)
        idx = z.argsort()
        x, y, z = data[idx, ind*2], data[idx, ind*2+1], z[idx]

        ax=plt.subplot(3, 2, plot_index[ind])
        plt.scatter(x, y,c=z, s=1,cmap='Spectral') # c表示标记的颜色
        plt.xlabel(f"{ind*2}")
        plt.ylabel(f"{ind*2+1}")
        plt.colorbar( orientation="vertical")
        x_major_locator = MultipleLocator(0.5)
        y_major_locator = MultipleLocator(0.5)
        ax.xaxis.set_major_locator(x_major_locator)
        ax.yaxis.set_major_locator(y_major_locator)


plt.show(block=True)
plt.close('all')
  • 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
  • 29
  • 30
  • 31
  • 32
  • 33

在这里插入图片描述

参考文献

[1] https://matplotlib.org/gallery/lines_bars_and_markers/scatter_star_poly.html#sphx-glr-gallery-lines-bars-and-markers-scatter-star-poly-py
[2] 如何用Matplotlib 画三维图的示例代码
[3] Matplotlib boxplot
[4] matplotlib交互式展示数据.ipynb
[5] matplotlib PickEvent
[6] matplotlib stem
[7] matplotlib colors
[8] csdn stem函数–Matplotlib
[9] Matplotlib scatter 3D button_press_event give wrong index based on scatter axis place on subplot


  1. https://www.cnblogs.com/ssrsblogs/p/6065403.html ↩︎

  2. Serif和Sans-serif字体的区别 ↩︎

  3. https://matplotlib.org/gallery/color/named_colors.html#sphx-glr-gallery-color-named-colors-py ↩︎

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/612743
推荐阅读
相关标签
  

闽ICP备14008679号