Python-matplotlib库常用分析图(双周,子图,极坐标,雷达等)


本篇文章包含了常用图形,其次有双坐标周,一个画布多个子图,极坐标图等等,仔细阅读加操作,相信收获是很大的。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'KaiTi'
plt.rcParams['axes.unicode_minus'] = False
%config InlineBackend.figure_format = 'svg'

图形绘制

# 1、图形绘制
x = np.linspace(0, 2*np.pi)  # x轴

y = np.sin(x)  # y轴 正弦
plt.figure(figsize=(6,4))  # 调整尺⼨(6,4)
plt.plot(x,y) # 绘制线形图
plt.plot(x, np.cos(x))
# 继续调⽤plot绘制多条线形图

plt.grid(axis='both',  # 画线的轴,以x轴为基础
        color='r',  # 网格线的颜色
        linestyle='--',  
        linewidth=1,
        alpha=0.5)

# 2、设置坐标轴范围
plt.xlim([-1,7])
plt.ylim([-1.5,1.5])
(-1.5, 1.5)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WPJALoVG-1615366952273)(output_2_1.svg)]

坐标轴刻度、标签、标题

plt.figure(figsize=(6,4), dpi=80)
plt.plot(x, y)
# 1、设置x,y轴刻度
plt.xticks(np.arange(0,2*np.pi+0.1,np.pi/2), 
           labels=['0',r'$\frac{\pi}{2}$', r'$\pi$',r'$\frac{3\pi}{2}$', r'$2\pi$'],
           fontsize=13,
           color='red')


# 2、设置x,y轴刻度标签
plt.yticks(ticks = np.arange(-1,1.01,0.5),
               labels = ['min', 'middle', '0', 'middle', 'max'],
               fontsize=12, ha='right')

plt.title('正弦函数')
plt.ylabel('y = sin(x)', rotation=0,
          horizontalalignment = 'center',
          fontstyle = 'normal',
          fontsize= 12)
Text(0, 0.5, 'y = sin(x)')

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d3OvxbV0-1615366952278)(output_4_1.svg)]

图例

x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
plt.plot(x, y1)
plt.plot(x, y2)
plt.legend(['sin', 'cos'], fontsize=13, loc='center', ncol=2,
          bbox_to_anchor=[0,1.01,1,0.2])

<matplotlib.legend.Legend at 0x1de229f0040>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t8U6613z-1615366952280)(output_6_1.svg)]

脊柱移动(坐标轴移动)

x = np.linspace(-np.pi, np.pi)
plt.plot(x, np.sin(x), x, np.cos(x))
ax = plt.gca()  # Get the current axes,获取当前视图

# 右边和上面线条小时
ax.spines['right'].set_color('white')
ax.spines['top'].set_color('white')

# 设置下边线条和左边线条位置,data表示数据,axes表示相对位置0-1
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

# 调整坐标轴刻度
plt.yticks(ticks=[-1, -0.5, 0, 0.5, 1],
          labels=[-1, -0.5, 0, 0.5, 1])

_ = plt.xticks(ticks=[-np.pi,-np.pi/2,np.pi/2,np.pi],
          labels=[r'$-\pi$', r'$-\frac{\pi}{2}$',
                  r'$\frac{\pi}{2}$', r'$-\pi$'])

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sPsjFr7S-1615366952285)(output_8_0.svg)]

图片保存

y = np.sin(x)   # 正弦波
plt.figure(linewidth = 4)
plt.plot(x, y, color = 'red')
plt.plot(x, np.cos(x), color = 'k')  # 余弦波
ax = plt.gca()  # 获取视图
ax.set_facecolor('lightgreen') # 设置视图背景颜⾊
# 2、图例
plt.legend(['Sin','Cos'],fontsize = 18,loc = 'center',ncol = 2,bbox_to_anchor =[0, 1.01, 1, 0.2])
plt.tight_layout() # ⾃动调整布局空间,就不会出现图⽚保存不完整
# plt.savefig('./基础5.png', # ⽂件名:png、jpg、pdf
#             dpi = 100, # 保存图⽚像素密度
#             facecolor = 'violet', # 视图与边界之间颜⾊设置
#             edgecolor = 'lightgreen', # 视图边界颜⾊设置
#             bbox_inches = 'tight')# 保存图⽚完整

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IH20gyjM-1615366952288)(output_10_0.svg)]

def f(x):
    return np.exp(-x)*np.cos(2*np.pi*x)

x = np.linspace(0,5,40)
plt.figure(figsize=(6,4))
plt.plot(x, f(x), c='purple',
        marker = 'o', ls='--',
        lw = 2, alpha=0.5,
        markerfacecolor='red',      # 点颜色
        markersize = 6,             # 点大小
        markeredgecolor = 'green',  # 点边缘颜色
        markeredgewidth = 3 )       # 点边缘宽度  
[<matplotlib.lines.Line2D at 0x1de227a6a60>]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lIcWBB6j-1615366952291)(output_11_1.svg)]

多图布局

子视图

x = np.linspace(-3,3,50)
ax = plt.subplot(221)
ax.set_facecolor('green')
ax.plot(x, np.sin(x), c='red')

ax = plt.subplot(222)
ax.plot(x, -np.sin(x), marker='*',markeredgecolor='green',
       markerfacecolor='red')

ax = plt.subplot(2, 1, 2)
plt.sca(ax)
plt.plot(x, np.sin(x*x), color = 'red')
[<matplotlib.lines.Line2D at 0x280f7c5ca90>]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YGismLRh-1615366952293)(output_14_1.svg)]

嵌套

x = np.linspace(-np.pi,np.pi,100)
y = np.sin(x)
fig = plt.figure(figsize=(8, 5)) # 创建视图
plt.plot(x, y)

# 嵌套⽅式⼀,axes轴域(横纵坐标范围),⼦视图
ax = plt.axes([0.2,0.55,0.3,0.3]) # 参数含义[left, bottom, width, height]
ax.plot(x,y,color = 'g')

ax = fig.add_axes([0.55, 0.2, 0.3, 0.3])
ax.plot(x, y, c='r')
[<matplotlib.lines.Line2D at 0x1de2d9fbb80>]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-OhD4nfbv-1615366952295)(output_16_1.svg)]

均匀布局

x = np.linspace(0,2*np.pi)
fig, ((ax11, ax12, ax13),(ax21, ax22, ax23),(ax31, ax32, ax33)) = plt.subplots(3,3)
fig.set_figwidth(10)
fig.set_figheight(8)
ax11.plot(x,np.sin(x))
ax12.plot(x,np.cos(x))
ax13.plot(x,np.tanh(x))
ax21.plot(x,np.tan(x))
ax22.plot(x,np.cosh(x))
ax23.plot(x,np.sinh(x))
ax31.plot(x,np.sin(x) + np.cos(x))
ax32.plot(x,np.sin(x*x) + np.cos(x*x))
ax33.plot(x,np.sin(x)*np.cos(x))

# 紧凑显示
plt.tight_layout()
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-17-6d3ea94aad19> in <module>
      4 fig.set_figheight(8)
      5 ax11.plot(x,np.sin(x))
----> 6 ax11.title('kkkk')
      7 ax12.plot(x,np.cos(x))
      8 ax13.plot(x,np.tanh(x))


TypeError: 'Text' object is not callable

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EQ0vWe4W-1615366952297)(output_18_1.svg)]

不均匀分布

x = np.linspace(0,2*np.pi,200)
fig = plt.figure(figsize=(7,5))

ax1 = plt.subplot(3,1,1) # 视图对象添加⼦视图
ax1.plot(x,np.sin(10*x))
# 设置ax1的标题,xlim、ylim、xlabel、ylabel等所有属性现在只能通过set_属性名的⽅法设置
ax1.set_title('ax1_title') # 设置⼩图的标题

ax2 = plt.subplot(3, 3, (4,5))  # (*nrows*, *ncols*, *index*)
ax2.set_facecolor('green')
ax2.plot(x,np.cos(x),color = 'red')

ax3 = plt.subplot(3,3,(6,9))
ax3.plot(x,np.sin(x) + np.cos(x))

ax4 = plt.subplot(3,3,7)
ax4.plot(x,x)

ax5= plt.subplot(3,3,8)
ax5.scatter(x[::20],x[::20], alpha=0.7)
ax5.set_xlabel('ax5_x',fontsize = 12)
ax5.set_ylabel('ax5_y',fontsize = 12)

plt.tight_layout()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RUWohUhv-1615366952299)(output_20_0.svg)]

方式二

x = np.linspace(0, 2*np.pi, 100)
plt.figure(figsize=(7,5))

ax1 = plt.subplot2grid(shape = (3,3),
                      loc = (0,0),
                      colspan = 3) # 跨几列
ax1.plot(x, np.sin(x))
ax1.set_title('ax1_title') # 设置⼩图的标题

ax2 = plt.subplot2grid(shape=(3,3), loc=(1,0), colspan=2)
ax2.plot(x, -np.sin(x))

ax3 = plt.subplot2grid(shape=(3,3), loc=(2,0), colspan=1)
ax3.plot(x, (x))

ax4 = plt.subplot2grid(shape=(3,3), loc=(2,1), colspan=1)
ax4.plot([0,1,2], [2,5,6])

ax5 = plt.subplot2grid(shape=(3,3), loc=(1,2), rowspan=2)
ax5.plot(x, np.sin(x+x))
[<matplotlib.lines.Line2D at 0x1de2ed782b0>]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0hfxfGPs-1615366952301)(output_22_1.svg)]

双轴显示

x = np.arange(1,5)
y = np.random.randint(100,130,4)
data1 = np.exp(x)
data2 = np.sin(x)

plt.figure(figsize=(7,5))
ax1 = plt.gca()
ax1.plot(x, y, c='red', marker='o')
plt.xticks(ticks=x, labels=['一季度','二季度','三季度','四季度'])
plt.yticks(ticks=[105,110, 115, 120, 125], labels=[105,110, 115, 120, 125])
ax1.set_xlabel('时间') # 设置x轴标签
ax1.set_ylabel('销量', rotation = 0, color='red', ha='right') # 设置y轴标签
ax1.tick_params(axis='y', labelcolor='red') # 设置y轴刻度属性

# 公用一个x轴
ax2 = ax1.twinx() 
ax2.set_ylabel('增长率(%)', color='b', rotation=0, ha='left')
y_ = [str(i)+'%' for i in  np.concatenate([[0],np.round((y[1:] - y[:-1])/y[:-1]*100, 2)])]
ax2.plot(x, y_, c='blue', marker='o')
ax2.tick_params(axis='y', labelcolor='blue')
plt.tight_layout() # 紧凑布局

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yg2vonGK-1615366952304)(output_24_0.svg)]

文本、注释、箭头

x = np.linspace(0.0, 5.0, 1000)
y = np.cos(2*np.pi*x) * np.exp(-x)
plt.figure(figsize=(9,6))
plt.plot(x, y, 'k')
plt.title('exponential decay',fontsize = 18)
plt.suptitle('指数衰减',y = 1.05,fontsize = 12)

plt.text(x = 2, y = 0.65,   # 横纵坐标位置
         s = r'$\cos(2 \pi x) \exp(-x)$') # ⽂本内容

plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uPwn4bvI-1615366952306)(output_26_0.svg)]

注释

fig, ax = plt.subplots()
x = np.arange(0.0, 5.0, 0.01)
y = np.cos(2*np.pi*x)
line, = ax.plot(x,y,lw=1)
ax.annotate('local max', # ⽂本内容
            xy=(2, 1), # 箭头指向位置
            xytext=(3, 1.5), # ⽂本位置
            fontsize=12,
            arrowprops=dict(facecolor='black', width=1, headwidth=6, headlength=7, shrink=0.1)) # 箭头

ax.annotate('local min',
            xy = (2.5,-1),
            xytext = (3.2,-1.5),
            fontsize=12,
            arrowprops = dict(facecolor = 'black',
                               width = 1, # 箭头宽度
                               headwidth = 6,# 箭头头部宽度
                               headlength = 7, # 箭头头部⻓度
                               shrink = 0.1
                               )) # 箭头两端收缩的百分⽐(占总⻓)

ax.annotate('median',
            xy = (2.25,0),
            xytext = (1,-1.5),
            arrowprops = dict(arrowstyle = '-|>'), # 箭头样式
            fontsize = 12)

ax.set_ylim(-2, 2)
(-2.0, 2.0)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5pyze2HM-1615366952309)(output_28_1.svg)]

def annotate_con_style(ax, connectionstyle):
    x1, y1 = 3,2
    x2, y2 = 8,6
    ax.plot([x1, x2], [y1, y2], ".")
    ax.annotate(s = '',
    xy=(x1, y1), # 相当于B点,arrow head
    xytext=(x2, y2), # 相当于A点,arrow tail
    arrowprops=dict(arrowstyle='->', color='red',
    shrinkA = 5,shrinkB = 5,
    connectionstyle=connectionstyle))
    ax.text(.05, 0.95, connectionstyle.replace(",", "\n"),
    transform=ax.transAxes, # 相对坐标
    ha="left", va="top")# 指定对⻬⽅式
# 常⽤箭头连接样式
fig, axs = plt.subplots(3, 5, figsize=(7,6))
annotate_con_style(axs[0, 0], "angle3,angleA=90,angleB=0")
annotate_con_style(axs[1, 0], "angle3,angleA=0,angleB=90")
annotate_con_style(axs[2, 0], "angle3,angleA = 0,angleB=150")
#     第六部分 常⽤视图
#     第⼀节 折线图
annotate_con_style(axs[0, 1], "arc3,rad=0.")
annotate_con_style(axs[1, 1], "arc3,rad=0.3")
annotate_con_style(axs[2, 1], "arc3,rad=-0.3")
annotate_con_style(axs[0, 2], "angle,angleA=-90,angleB=180,rad=0")
annotate_con_style(axs[1, 2], "angle,angleA=-90,angleB=180,rad=5")
annotate_con_style(axs[2, 2], "angle,angleA=-90,angleB=10,rad=5")
annotate_con_style(axs[0, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0")
annotate_con_style(axs[1, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5")
annotate_con_style(axs[2, 3], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0")
annotate_con_style(axs[0, 4], "bar,fraction=0.3")
annotate_con_style(axs[1, 4], "bar,fraction=-0.3")
annotate_con_style(axs[2, 4], "bar,angle=180,fraction=-0.2")

for ax in axs.flat:
    # 设置轴域刻度
    ax.set(xlim=(0, 10), ylim=(0, 10),xticks = [],yticks = [],aspect=1)
    fig.tight_layout(pad=0.2)
<ipython-input-13-c9ef09ccc2c6>:5: MatplotlibDeprecationWarning: The 's' parameter of annotate() has been renamed 'text' since Matplotlib 3.3; support for the old name will be dropped two minor releases later.
  ax.annotate(s = '',

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-zBx7ABin-1615366952311)(output_29_1.svg)]

常用视图

x = np.random.randint(0,10,size = 15)
# ⼀图多线
plt.figure(figsize=(6,5))
plt.plot(x,marker = '*',color = 'r')
plt.plot(x.cumsum(),marker = 'o')

# 多图布局
fig,axs = plt.subplots(2,1)
fig.set_figwidth(6)
fig.set_figheight(5)
axs[0].plot(x,marker = '*',color = 'red')
axs[1].plot(x.cumsum(),marker = 'o')
[<matplotlib.lines.Line2D at 0x1de2a909670>]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HO1In2eC-1615366952313)(output_31_1.svg)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b2NciAL6-1615366952315)(output_31_2.svg)]

柱状图

labels = ['G1', 'G2', 'G3', 'G4', 'G5','G6'] # 级别
men_means = np.random.randint(20,35,size = 6)
women_means = np.random.randint(20,35,size = 6)
men_std = np.random.randint(1,7,size = 6)
women_std = np.random.randint(1,7,size = 6)
width = 0.35
plt.bar(labels,   # 横坐标x
       men_means, # 柱高
       width,
       yerr=3, # 误差条
       label='Men')
plt.bar(labels, women_means, width, yerr=3, label='Women', bottom=men_means)
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.legend()
<matplotlib.legend.Legend at 0x2e2be6e8b50>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7qPEUUjU-1615366952317)(output_33_1.svg)]

x = np.arange(1,7)
rects1 = plt.bar(x-width/2, women_means, width, label='Women')
rects2 = plt.bar(x+width/2, men_means, width, label='Men')
# 设置标签标题,图例
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(x,labels)
plt.legend()

def set_text(rects):
    for rect in rects:
        height = rect.get_height() # 获取高度
        plt.text(x = rect.get_x()+ rect.get_width()/2,
                y = height + 0.5,
                s = height , # 文本
                ha = 'center')
        
set_text(rects1)
set_text(rects2)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Cw2tmM4b-1615366952319)(output_34_0.svg)]


极坐标图

极坐标线性图
r = np.arange(0, 4*np.pi, 0.01) # 弧度值
y = np.linspace(0,2,len(r)) # ⽬标值
ax = plt.subplot(111, projection='polar', facecolor = 'lightgreen') # 定义极坐标)
ax.plot(r, y, color='red')
ax.set_rmax(3)   # 设置半径最大值
ax.set_rticks([0.5, 1.5, 2.5])  # 设置半径刻度
ax.set_rlabel_position(0)
ax.grid(True)  # 网格线

ax.set_title('A B', va='center', ha='center', pad=30)
Text(0.5, 1.0, 'A B')

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4ZZiUzf0-1615366952321)(output_38_1.svg)]

极坐标柱状图
n = 8
theta = np.linspace(0, 2*np.pi, n, endpoint=False)
rad = np.random.randint(3,15,size=n)
width = np.pi / 4
colors = np.random.rand(8, 3)

ax = plt.subplot(111, projection='polar')
ax.set_rmax(14)
ax.set_rticks([2,6,10,14])
ax.grid(False)
ax.bar(theta, rad, width=width, bottom=0,color = colors)

plt.axis('off')
(0.0, 6.283185307179586, 0.0, 14.7)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gUvh5VS8-1615366952323)(output_40_1.svg)]

rad
array([11, 11,  3,  4, 11,  4, 14,  7])

直方图

mu = 10
sigma = 5
x = np.random.normal(loc=mu, scale=sigma, size=100000)
fig, ax = plt.subplots()

# 概率密度
n, bins, patches = ax.hist(x, 1000, density=True, alpha=0.8) # 直⽅图
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu))**2))
plt.plot(bins, y, '--')
[<matplotlib.lines.Line2D at 0x280f7cd9250>]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wSdcMopa-1615366952326)(output_43_1.svg)]

箱型图

data=np.random.normal(size=(500,4))
lables = ['A','B','C','D']
# ⽤Matplotlib画箱线图
_ = plt.boxplot(data,
                notch = 1,
                sym = 'g',
                labels=lables) # 红⾊的圆点是异常值

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-unGy60R7-1615366952328)(output_45_0.svg)]

散点图

data = np.random.randn(50,2)
size = np.random.randint(50,300,size = 50)
color = np.random.randn(50)
plt.scatter(data[:,0], # 横坐标
            data[:,1], # 纵坐标
            s = size, # 尺⼨
            c = color, # 颜⾊
            alpha = 0.5) # 透明度
<matplotlib.collections.PathCollection at 0x2e2c0125df0>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EWpIQM2e-1615366952330)(output_47_1.svg)]

饼图

一般饼图
labels =["五星","四星","三星","two星","one星"] # 标签

percent = [95,261,105,30,9] # 某市星级酒店数量
# 设置图⽚⼤⼩和分辨率
fig=plt.figure(figsize=(5,5), dpi=80)
# 偏移中心量
explode = (0, 0.1, 0, 0, 0)

# 绘制饼图
_ = plt.pie(x=percent, # 数据
       explode = explode,  # 偏移量
       labels = labels, # 显示标签
       autopct='%.1f%%',  # 显示百分比
       shadow=True) # 阴影,3D效果

plt.savefig('./pie.png')

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0Qm8bZKa-1615366952332)(output_50_0.svg)]

嵌套饼图
fig=plt.figure(figsize=(5,5),dpi=100)
#数据集,p1, p2分别对应外部、内部百分⽐例
p1=[43,25,32]
p2=[7,22,14,]

labels = ['cat', 'dog', 'pig']
def f(pct):
    return r'%0.1f' % pct + '%'

_ = plt.pie(p1,
       autopct='%.2f%%', # lambda pct: f(pct)
       radius=1, # 半径
       pctdistance=0.8, #百分比数字位置
       wedgeprops=dict(linewidth=5,  # 交接处间隙
                      width=0.4, # 圆环宽度
                      edgecolor='w'),
        # 饼图格式:间隔线宽、饼图宽度、边界颜⾊
       labels=labels)

# 给内部饼图画图
_ = plt.pie(p2,
       autopct='%.2f%%',
       radius=0.6,
       pctdistance=0.7,
       wedgeprops=dict(linewidth=3,
                      width=0.3,
                      edgecolor='white'))

# 设置图例标题、位置,frameon控制是否显示图例边框,bbox_to_anchor控制图例显示在饼图的外⾯
plt.legend(labels, 
           loc='upper right', 
           bbox_to_anchor=[0.75,0,0.4,1],
           title='宠物占比')
<matplotlib.legend.Legend at 0x280fa02df10>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RN9ZzlrD-1615366952335)(output_52_1.svg)]

甜甜圈案例(鸡肋)
plt.figure(figsize=(7,5))
# 甜甜圈原料
recipe = [  "225g flour",
            "90g sugar",
            "1 egg",
            "60g butter",
            "100ml milk",
            "1/2package of yeast"]
# 原料⽐例
data = [225, 90, 50, 60, 100, 5]
wedges, texts = plt.pie(data, startangle=40)
# 增加箭头指向
bbox_props = dict(boxstyle="square,pad=0.3", fc="lightgreen", ec="k", lw=0.78)
kw = dict(arrowprops=dict(arrowstyle="-"),
          bbox=bbox_props,va="center")

for i,p in enumerate(wedges):
    ang = (p.theta2-p.theta1)/2 + p.theta1  # 角度计算
    # ⻆度转弧度----->弧度转坐标
    y = np.sin(np.deg2rad(ang))
    x = np.cos(np.deg2rad(ang))
    ha = {-1: "right", 1: "left"}[int(np.sign(x))] # ⽔平对⻬⽅式
    connectionstyle = "angle,angleA=0,angleB={}".format(ang) # 箭头连接样式
    kw["arrowprops"].update({"connectionstyle": connectionstyle}) # 更新箭头连接式
    plt.annotate(recipe[i], 
                 xy=(x, y), 
                 xytext=(1.35*np.sign(x), 1.4*y),
                 ha=ha,**kw,fontsize = 18,
                 weight = 'bold')
    
plt.title("Matplotlib bakery: A donut",fontsize = 18,pad = 25)
plt.tight_layout()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3cNiuIrd-1615366952337)(output_54_0.svg)]

harvest
array([[1.36835925, 4.7502659 , 0.52811777, 0.50814274, 4.555695  ],
       [1.87560487, 2.25517527, 1.58325274, 2.74349702, 1.22924528],
       [1.01847642, 4.51211476, 1.27337548, 0.60192293, 2.00368841],
       [2.77175638, 0.64391426, 0.80853652, 3.7715786 , 4.15215521],
       [0.39090138, 2.02758888, 4.24475763, 4.14859812, 2.65742634]])

热力图

vegetables = ["cucumber", "lettuce", "asparagus", "wheat", "barley"]
farmers = list('ABCDE')
harvest = np.random.rand(5,5)*5 # 农⺠丰收数据
plt.figure(figsize=(7,5), dpi=100)
im = plt.imshow(harvest)
plt.xticks(ticks=np.arange(len(farmers)),
           labels=farmers,
           rotation = 0,
           ha = 'right')

plt.yticks(np.arange(len(vegetables)),vegetables)
for i in range(len(vegetables)):
    for j in range(len(farmers)):
        text = plt.text(j, i, round(harvest[i, j], 1),
                       ha='center', va='center',
                       color='red')
        
plt.title("Harvset of local farmers (in tons/year)", pad=30)
plt.tight_layout()
plt.savefig('./热力图.jpg')

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FnXW03bu-1615366952338)(output_57_0.svg)]

面积图

plt.figure(figsize=(6,5))
X = [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]
plt.stackplot(X, sleeping,eating,working,playing)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Stack Plot',fontsize = 12)
plt.legend(['Sleeping','Eating','Working','Playing'],
           bbox_to_anchor=(0.6,0.8,0.5,0.5),fontsize = 12)
<matplotlib.legend.Legend at 0x2e2bec318b0>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KhPEHcc6-1615366952341)(output_59_1.svg)]

蜘蛛图

labels = ['math','eng','chinese','physics', 'chemistry']
scores = np.random.randint(50,150,5)
scores = np.concatenate([ scores,[ scores[0] ] ])
# 画图数据准备, 角度,标签,分数
angles = np.linspace(0, 2*np.pi, 5, endpoint=False)

angles = np.concatenate([angles, [ angles[0] ] ])
fig = plt.figure(figsize=(6,5))
ax = fig.add_subplot(111, polar=True)
ax.plot(angles, scores, marker='o')
ax.fill(angles, scores, color='lightgreen')

# 设置角度
ax.set_thetagrids(angles[:-1]*180/np.pi, # 角度值
                 labels, fontsize=12)
ax.set_rgrids([10,40,70,110], fontsize = 12)
(<a list of 4 Line2D gridline objects>,
 [Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, ''), Text(0, 0, '')])

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CAbte7PX-1615366952343)(output_61_1.svg)]

3D图

三维折线图散点图
from mpl_toolkits.mplot3d.axes3d import Axes3D
x = np.linspace(0,60,300)
y = np.sin(x)
z = np.cos(x)

fig = plt.figure(figsize=(6,5))
ax3d = Axes3D(fig)
ax3d.plot(x,y,z)
ax3d.set_xlabel('X')
ax3d.set_ylabel('Y')
ax3d.set_zlabel('Z')

# 3维散点图
ax3d.scatter(np.random.rand(50)*60,
             np.random.rand(50),
             np.random.rand(50),
             color = 'red',s = 60)
<mpl_toolkits.mplot3d.art3d.Path3DCollection at 0x2e2c153f520>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Quiomtpo-1615366952345)(output_64_1.svg)]

三维柱状图

from matplotlib.pyplot import MultipleLocator
season = np.arange(1,5)

fig = plt.figure(figsize=(6,5))
ax3 = Axes3D(fig)
for m in season:
    ax3.bar(np.arange(1, 4),
           np.random.randint(10,50,3),
            zdir='x',  # 在哪个方向上,一排排拜访
            zs=m, alpha=0.7,width=0.5
       )

ax3.set_xlabel('季度',fontsize = 12,color = 'red')
ax3.set_ylabel('月份',fontsize = 12,color = 'red')
ax3.set_zlabel('产量',fontsize = 12,color = 'red')

x_major_locator=MultipleLocator(1)
y_major_locator=MultipleLocator(1)
ax = plt.gca()
ax.xaxis.set_major_locator(x_major_locator)
ax.yaxis.set_major_locator(y_major_locator)
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值