设为首页收藏本站

安徽论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 13297|回复: 0

Python数据分析之Matplotlib的常用操作总结

[复制链接]

63

主题

497

回帖

944

积分

高级会员

Rank: 4

积分
944
发表于 2022-3-26 11:00:44 | 显示全部楼层 |阅读模式
网站内容均来自网络,本站只提供信息平台,如有侵权请联系删除,谢谢!
目录


使用准备

使用matplotlib需引入:
  1. import matplotlib.pyplot as plt
复制代码
通常2会配合着numpy使用,numpy引入:
  1. import numpy as np
复制代码
1、简单的绘制图像
  1. def matplotlib_draw():
  2.     # 从-1到1生成100个点,包括最后一个点,默认为不包括最后一个点
  3.     x = np.linspace(-1, 1, 100, endpoint=True)

  4.     y = 2 * x + 1
  5.     plt.plot(x, y)  # plot将信息传入图中
  6.     plt.show()  # 展示图片
复制代码


2、视图面板的常用操作
  1. def matplotlib_figure():
  2.     x = np.linspace(-1, 1, 100)
  3.     y1 = 2 * x + 1
  4.     y2 = x ** 2  # 平方

  5.     plt.figure()  # figure是视图面板
  6.     plt.plot(x, y1)

  7.     # 这里再创建一个视图面板,最后会生成两张图,figure只绘制范围以下的部分
  8.     plt.figure(figsize=(4, 4))  # 设置视图长宽
  9.     plt.plot(x, y2)

  10.     plt.show()
复制代码



3、样式及各类常用修饰属性
  1. def matplotlib_style():
  2.     x = np.linspace(-3, 3, 100)
  3.     y1 = 2 * x + 1
  4.     y2 = x ** 2  # 平方

  5.     # 限制xy输出图像的范围
  6.     plt.xlim((-1, 2))  # 限制x的范围
  7.     plt.ylim((-2, 3))  # 限制y的范围

  8.     # xy描述
  9.     plt.xlabel('I am X')
  10.     plt.ylabel('I am Y')

  11.     # 设置xy刻度值
  12.     # 从-2到2上取11个点,最后生成一个一维数组
  13.     new_sticks = np.linspace(-2, 2, 11)
  14.     plt.xticks(new_sticks)
  15.     # 使用文字代替数字刻度
  16.     plt.yticks([-1, 0, 1, 2, 3], ['level1', 'level2', 'level3', 'level4', 'level5'])

  17.     # 获取坐标轴 gca get current axis
  18.     ax = plt.gca()
  19.     ax.spines['right'].set_color('red')  # 设置右边框为红色
  20.     ax.spines['top'].set_color('none')  # 设置顶部边框为没有颜色,即无边框

  21.     # 把x轴的刻度设置为'bottom'
  22.     ax.xaxis.set_ticks_position('bottom')
  23.     # 把y轴的刻度设置为'left'
  24.     ax.yaxis.set_ticks_position('left')
  25.     # 设置xy轴的位置,以下测试xy轴相交于(1,0)
  26.     # bottom对应到0点
  27.     ax.spines['bottom'].set_position(('data', 0))
  28.     # left对应到1点
  29.     ax.spines['left'].set_position(('data', 1))  # y轴会与1刻度对齐

  30.     # 颜色、线宽、实线:'-',虚线:'--',alpha表示透明度
  31.     plt.plot(x, y1, color="red", linewidth=1.0, linestyle='--', alpha=0.5)
  32.     plt.plot(x, y2, color="blue", linewidth=5.0, linestyle='-')
  33.     plt.show()  # 这里没有设置figure那么两个线图就会放到一个视图里
复制代码


4、legend图例的使用
  1. def matplotlib_legend():
  2.     x = np.linspace(-3, 3, 100)
  3.     y1 = 2 * x + 1
  4.     y2 = x ** 2  # 平方

  5.     l1, = plt.plot(x, y1, color="red", linewidth=1.0, linestyle='--', alpha=0.5)
  6.     l2, = plt.plot(x, y2, color="blue", linewidth=5.0, linestyle='-')
  7.     # handles里面传入要产生图例的关系线,labels中传入对应的名称,
  8.     # loc='best'表示自动选择最好的位置放置图例
  9.     plt.legend(handles=[l1, l2], labels=['test1', 'test2'], loc='best')
  10.     plt.show()
复制代码


5、添加文字等描述
  1. def matplotlib_describe():
  2.     x = np.linspace(-3, 3, 100)
  3.     y = 2 * x + 1
  4.     plt.plot(x, y, color="red", linewidth=1.0, linestyle='-')

  5.     # 画点,s表示点的大小
  6.     x0 = 0.5
  7.     y0 = 2 * x0 + 1
  8.     plt.scatter(x0, y0, s=50, color='b')

  9.     # 画虚线,
  10.     # k代表黑色,--代表虚线,lw线宽
  11.     # 表示重(x0,y0)到(x0,-4)画线
  12.     plt.plot([x0, x0], [y0, -4], 'k--', lw=2)
  13.     # 标注,xytext:位置,textcoords设置起始位置,arrowprops设置箭头,connectionstyle设置弧度
  14.     plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xytext=(+30, -30),
  15.                  textcoords="offset points", fontsize=16,
  16.                  arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))

  17.     # 文字描述
  18.     plt.text(-3, 3, r'$this\ is\ the\ text$', fontdict={'size': '16', 'color': 'r'})

  19.     plt.show()
复制代码


6、不同类型图像的绘制

(1)scatter绘制散点图:
  1. def matplotlib_scatter():
  2.     plt.figure()
  3.     plt.scatter(np.arange(5), np.arange(5))  # 安排两个0到4的数组绘制

  4.     x = np.random.normal(0, 1, 500)  # 正态分布的500个数
  5.     y = np.random.normal(0, 1, 500)

  6.     plt.figure()
  7.     plt.scatter(x, y, s=50, c='b', alpha=0.5)

  8.     plt.show()
复制代码


(2)bar绘制直方图:
  1. def matplotlib_bar():
  2.     x = np.arange(10)
  3.     y = 2 ** x + 10
  4.     # facecolor块的颜色,edgecolor块边框的颜色
  5.     plt.bar(x, y, facecolor='#9999ff', edgecolor='white')
  6.     # 设置数值位置
  7.     for x, y in zip(x, y):  # zip将x和y结合在一起
  8.         plt.text(x + 0.4, y, "%.2f" % y, ha='center', va='bottom')

  9.     plt.show()
复制代码

(3)contour轮廓图:
  1. def matplotlib_contours():
  2.     def f(a, b):
  3.         return (1 - a / 2 + a ** 5 + b ** 3) * np.exp(-a ** 2 - b ** 2)

  4.     x = np.linspace(-3, 3, 100)
  5.     y = np.linspace(-3, 3, 100)

  6.     X, Y = np.meshgrid(x, y)  # 将x和y传入一个网格中
  7.     # 8表示条形线的数量,数量越多越密集
  8.     plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)  # cmap代表图的颜色

  9.     C = plt.contour(X, Y, f(X, Y), 8, color='black', linewidth=.5)
  10.     plt.clabel(C, inline=True, fontsize=10)

  11.     plt.xticks(())
  12.     plt.yticks(())
  13.     plt.show()
复制代码

(4)3D图:
3D图绘制需额外再引入依赖:
  1. from mpl_toolkits.mplot3d import Axes3D
复制代码
  1. def matplotlib_Axes3D():
  2.     fig = plt.figure()  # 创建绘图面版环境
  3.     ax = Axes3D(fig)  # 将环境配置进去

  4.     x = np.arange(-4, 4, 0.25)
  5.     y = np.arange(-4, 4, 0.25)
  6.     X, Y = np.meshgrid(x, y)  
  7.     R = np.sqrt(X ** 2 + Y ** 2)
  8.     Z = np.sin(R)

  9.     # stride控制色块大小
  10.     ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
  11.     ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow')
  12.     ax.set_zlim(-2, 2)

  13.     plt.show()
复制代码


(5)subplot子图绘制:
  1. def matplotlib_subplot():
  2.     plt.figure()  # 生成绘图面板
  3.     plt.subplot(2, 1, 1)  # 两行1列绘图位置的第1个位置
  4.     plt.plot([0, 1], [0, 1])  # 绘制从(0,0)绘制到(1,1)的图像
  5.     plt.subplot(2, 3, 4)  # 两行3列绘图位置的第4个位置
  6.     plt.plot([0, 1], [0, 1])  # 绘制从(0,0)绘制到(1,1)的图像
  7.     plt.subplot(2, 3, 5)  # 两行3列绘图位置的第5个位置
  8.     plt.plot([0, 1], [0, 1])  # 绘制从(0,0)绘制到(1,1)的图像
  9.     plt.subplot(2, 3, 6)  # 两行3列绘图位置的第6个位置
  10.     plt.plot([0, 1], [0, 1])  # 绘制从(0,0)绘制到(1,1)的图像

  11.     plt.show()
复制代码

(6)animation动图绘制
需额外导入依赖:
  1. from matplotlib import animation
复制代码
  1. # ipython里运行可以看到动态效果
  2. def matplotlib_animation():
  3.     fig, ax = plt.subplots()

  4.     x = np.arange(0, 2 * np.pi, 0.01)
  5.     line, = ax.plot(x, np.sin(x))

  6.     def animate(i):
  7.         line.set_ydata(np.sin(x + i / 10))
  8.         return line,

  9.     def init():
  10.         line.set_ydata(np.sin(x))
  11.         return line,

  12.     ani = animation.FuncAnimation(fig=fig, func=animate, init_func=init, interval=20)

  13.     plt.show()
复制代码

附:直方图代码实现
  1. import numpy as np
  2. import matplotlib.pyplot as plt

  3. np.random.seed(1)
  4. # 产生30个学生身高数据
  5. hight = np.random.randint(low=140, high=190, size=30)
  6. print("身高数据", hight)

  7. # 绘制直方图 plt.hist

  8. # 参数1:要统计的数据; 参数2:区间信息

  9. # 区间信息有默认值 bins =10  分10组
  10. # bins = [140, 145, 160, 170, 190]
  11. # 除了最后一个 都是前闭后开;最后一组是前闭后闭
  12. # [140,145) [145,160) [160,170) [170,190]

  13. bins = [140, 180, 190]

  14. cnt, bins_info, _ = plt.hist(hight,
  15.                              bins=10,
  16.                              # bins=bins,
  17.                              edgecolor='w'  # 柱子的边缘颜色 白色
  18.                              )
  19. # 直方图的返回值有3部分内容
  20. # 1. 每个区间的数据量
  21. # 2. 区间信息
  22. # 3. 区间内数据数据信息 是个对象 不能直接查看
  23. # print("直方图的返回值", out)

  24. # cnt, bins_info, _ = out


  25. # 修改x轴刻度
  26. plt.xticks(bins_info)

  27. # 增加网格线
  28. # 参数1:b bool类型 是否增加网格线
  29. # 参数 axis 网格线 垂直于 哪个轴
  30. plt.grid(b=True,
  31.          axis='y',
  32.          # axis='both'
  33.          alpha=0.3
  34.          )

  35. # 增加标注信息 plt.text
  36. print("区间信息", bins_info)
  37. print("区间数据量", cnt)

  38. bins_info_v2 = (bins_info[:-1] + bins_info[1:]) / 2
  39. for i, j in zip(bins_info_v2, cnt):
  40.     # print(i, j)
  41.     plt.text(i, j + 0.4, j,
  42.              horizontalalignment='center',  # 水平居中
  43.              verticalalignment='center',  # 垂直居中
  44.              )

  45. # 调整y轴刻度
  46. plt.yticks(np.arange(0, 20, 2))

  47. plt.show()
复制代码

更多见官方文档:教程 | Matplotlib 中文

总结

到此这篇关于Python数据分析之Matplotlib常用操作的文章就介绍到这了,更多相关Python Matplotlib常用操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
                                                        
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
免责声明
1. 本论坛所提供的信息均来自网络,本网站只提供平台服务,所有账号发表的言论与本网站无关。
2. 其他单位或个人在使用、转载或引用本文时,必须事先获得该帖子作者和本人的同意。
3. 本帖部分内容转载自其他媒体,但并不代表本人赞同其观点和对其真实性负责。
4. 如有侵权,请立即联系,本网站将及时删除相关内容。
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表