Matplotlib画图笔记
郝伟 2020/12/09

推荐资源

使用方法很简单,只要三步:

  1. 导出 *.ipynb 文件
  2. 上传至 github或任何可访问的网址
  3. 将文件链接复制至nbviewer页面中进行转换即可

示例:

  1. 生成notepad.ipynb文件
  2. 上传至 http://121.199.10.158:8107/tests/notebook.ipynb
  3. 在https://nbviewer.jupyter.org/输入第2步的地址,即可在以下网址访问:
    https://nbviewer.jupyter.org/url/121.199.10.158:8107/tests/notebook.ipynb

具体可以参考此文:https://www.cnblogs.com/everfight/p/ipynb_sharing.html

matplotlib 直方图绘制代码和效果

首先,看代码和运行效果。

import numpy as np
import matplotlib.pyplot as plt

# 修改全局的边框线宽为1
plt.rcParams['axes.linewidth'] = 1

# 设置字体为微软雅黑
plt.rcParams[ 'font.sans-serif'] = [ 'Microsoft YaHei']

# 设置四个边框是否显示刻度
plt.tick_params(left= True, right=False, top=False, bottom= 'on')

# 显示文字
plt.text(x, x, s, color, size, fontweight)

# 设置图形的显示风格
plt.style.use('fast')

# # 绘制颜色为红色、透明度为0.3、线形为虚线、宽度为0.5的网络,另 plt.grid(True) 直接显示
plt.grid(color = 'red', alpha = 0.3, linestyle = '--', linewidth = .5)
# plt.grid(True)

# 设置边框的颜色,除了left还有right,top,bottom
# plt.gca().spines['left'].set_color('darkgray')


#显示图例
plt.legend()

# 设置显示的总标题
plt.title('员工年龄分布示意图',fontsize=24)


# 设置坐标轴的显示范围
plt.xlim(19, 61)
#plt.ylim(0,12)

# 设置坐标轴的刻度
plt.xticks([20, 25, 30, 35, 40, 45, 50, 55, 60])#[i * 5 + 15 for i in range(10)])
#plt.yticks([i for i in range(12)])

# 设置坐标轴文本
plt.xlabel('Values',fontsize=14)
plt.ylabel('员工',fontsize=14)


# 员工年龄频数直方图
x, bins, _ = plt.hist(ages,           # 绘图数据
         bins = [20, 25, 30, 35, 40, 45, 50, 55, 60],  # 指定直方图的条形数为20个
         range=(15,50),  # 指定所要显示的范围,当其与bins不一致时,以bins为准
#        normed=True,
        rwidth = 0.9,
#        align='left',
#        cumulative=True,
#        histtype='stepfilled',
#        bottom = 10,
#        center='mid',
#        weights = ages * 10,
#        orientation='horizontal',
        color = 'lightgray', # 指定填充色
        edgecolor = 'black', # 指定直方图的边界色
        label = '员工年龄分布') # 为直方图呈现标签

# 在每个条形上方添加数字,坐标是计算出来的
for index, value in enumerate(x): 
    plt.text(x=index * 5 + 21.5, 
             y=value + 0.1 , 
             s=f'{int(value)}', 
             color='black', 
             size=14, 
             fontweight='bold')

# 在指定的坐标显示文本,文本支持LaTeX
# plt.text(40, 10, r'$\mu=100,\ \sigma=15$')
plt.show()

显示效果如下所示
image

绘制lines

import matplotlib.pyplot as plt
import numpy as np

xs = np.arange(0, 6)
ys = np.array([0.2, 1.3, 2.1, 2.9, 4.3, 4.8])
ys1 = xs + 0.1
y_bar = np.mean(ys)

# 设置坐标轴文本
plt.xlabel('X', fontsize=14)
plt.ylabel('Y', fontsize=14)

plt.xlim(-0.5, 5.5)
plt.ylim(-0.5, 5.5)
plt.plot(xs, ys,'o', color='black')
plt.plot([-1, 10], [-1, 10], '-', color='red')
plt.plot([-10, 10], [y_bar, y_bar], color='blue')

#plt.axes.
for i in range(len(ys)):
    xs3 = np.array([i, i])
    ys3 = np.array([y_bar, ys[i]])
    plt.plot(xs3, ys3, '--', color='black', linewidth='0.5')
    plt.text(i+0.2, ys[i] - 0.2, str(ys[i]))

plt.text(0.5, 2.65, r"$\bar{y}$", fontweight=26)
plt.text(3.5, 3.80, r"$\hat{y}$", fontweight=26)
plt.text(3.5, 4.80, r"$\{$", fontweight=26)
# plt.plot(3, 1,'o');

box=dict(fc="red",pad=2,alpha=0.4)
#给坐标轴的标签加上文本框,就是使用bbox函数
plt.xlabel("xaxis",bbox=box)

# 上方斜线,展示如何使用LaTeX
plt.plot([1,2,3], [4,5,6], color='b', label=r'Mean ROC (AUC = %0.2f $\pm$ %0.2f)' % (3.5, 4.6), lw=2, alpha=.8)

plt.show()

绘制效果
image

bar() 函数

简单入门示例,使用以下代码可以得到图1所示效果。

import numpy as np
import matplotlib.pyplot as plt

# x和y轴上的数据分别用两个数列表示
xs = range(20)
ys = np.random.randint(18, high=61, size=len(xs))

# 绘制bar,其中xs和ys是必需的,其他参数可选
plt.bar(xs, ys, width=1, color='b', edgecolor='black')
plt.show()

image

hist()函数

hist函数的参数有很多,如下所示:
主要参数作用

[1] matplotlib.pyplot.hist API, matplotlib.org, https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html
[2] 特别好的一个tutorial, https://www.datacamp.com/community/tutorials/matplotlib-tutorial-python
[3] 太赞了!100个案例,Matplotlib 从入门到大神!(附源代码), https://blog.csdn.net/SeizeeveryDay/article/details/110729889