Matplotlib画图笔记
郝伟 2020/12/09
官方matplot.pyplot库参考文档
https://matplotlib.org/api/_as_gen/matplotlib.pyplot.html
nbviewer A simple way to share Jupyter Notebooks
非常强大的工具,能够直接将notebook的内容输出为可视的Html进行在线演示,比如此示例:AnatomyOfMatplotlib-Part0-Intro2NumPy.。
Matplotlib Tutorial: Python Plotting
This Matplotlib tutorial takes you through the basics Python data visualization: the anatomy of a plot, pyplot and pylab, and much more
使用方法很简单,只要三步:
示例:
具体可以参考此文:https://www.cnblogs.com/everfight/p/ipynb_sharing.html
首先,看代码和运行效果。
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()
显示效果如下所示

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()
绘制效果

简单入门示例,使用以下代码可以得到图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()

hist函数的参数有很多,如下所示:
主要参数作用
x:指定所要制的数据,此数据常用的是一维列表数据,记录同一维度的分散数据(后详);
bins:在英文中bin指的是小盒子,所以这里指定直方图上的条形,指定的方式有两种:
第1种是固定值,表示其数量,然后由其自主分配;
第2种是数列,如[5,10,15],那么在坐标轴上就会显示 5 10 15 这三个标签;
range:指定直方图数据x轴的上下界[start, end);
bottom:指定y轴的下限,默认为0;
normed:是否将直方图的频数转换成频率;
weights:该参数可为每一个数据点设置权重;
cumulative:是否需要计算累计,即第n个条形为前1-n个的累计和;
histtype:指定直方图的类型,默认为bar,除此还有’barstacked’, ‘step’, ‘stepfilled’;
rwidth:设置条形宽度的百分比,取值范围为[0,1];
align:设置条形的居中方式,相对于坐标刻度的位置,默认为值为’mid’表示在start和end中间,还有’left’和’right’;
orientation:设置直方图的方向,默认为垂直方向 ‘vertical’,水平是’horizontal’;
log:是否需要对数据进行对数变换;
color:设置条形的填充色;
edgecolor:条形的边缘的颜色;
label:设置直方图的标签,通过 plt.legend() 设置是否显示;
stacked:当有多个数据时,决定是否呈堆叠摆放,默认水平摆放;
[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