Matplotlib绘图基础

1.Figure和Subplot

import numpy as np
import matplotlib.pyplot as plt #创建一个Figure
fig = plt.figure() #不能通过空figure绘图,必须使用add_subplot创建一个或多个subplot
#图像为2x2,第三个参数为当前选中的第几个
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3) #默认在最后一个subplot上绘制
#'k--'为线型选项,绘制黑色虚线
plt.plot(np.random.randn(50).cumsum(), 'k--') print(type(ax1))#<class 'matplotlib.axes._subplots.AxesSubplot'>
#直接调用它们的实例方法就可以在其他格子绘图 _ = ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30)) plt.show()
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)#创建一个新的Figure,并返回一个已创建subplot对象的NumPy数组
#可以索引axes[0,1],axes[0][1] '''
plt.subplots的选项
nrows:subplot的行数
ncols:subplot的列数
sharex:所有subplot应该使用相同的x轴刻度(调节xlim将会影响所有subplot)
sharey:所有subplot应该使用相同的y轴刻度(调节ylim将会影响所有subplot)
subplot_kw:用于创建各subplot的关键字字典
**fig_kw:创建figure时其他关键字,如plt.subplots(2,2,figsize=(8,6))
''' for i in range(2):
for j in range(2):
axes[i,j].hist(np.random.randn(500),bins=50, color='k',alpha=0.5) #调整subplot周围间距
#plt.subplots_adjust(left=None,bottom=None,right=None,top=None,wspace=None,hspace=None)
plt.subplots_adjust(wspace=0, hspace=0) plt.show()

2.颜色、标记和线型

#ax.plot(x,y,'g--')
#ax.plot(x, y, linestyle='--', color='g') #plt.plot(np.random.randn(30).cumsum(), 'ko--')
#plt.plot(np.random.randn(30).cumsum(), color='k', linestyle='dashed', marker='o') #线型图中,非实际数据点默认是按线性方式插值的,可以通过drawstyle选项修改
data = np.random.randn(30).cumsum()
plt.plot(data, 'k--', label='Defalt')
plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post') plt.legend(loc='best')

3.刻度、标签和图例

xlim,xticks,xticklabels之类的方法。它们分别控制图表的范围、刻度位置、刻度标签等。

其使用方式有以下两种:

  • 调用时不带参数,则返回当前参数值。plt.xlim()
  • 调用时带参数,则设置参数值。plt.xlim([0,10])

这些方法对当前或最近创建的AxesSubplot起作用

对应在subplot对象上的两个方法,如ax.get_xlim和ax.set_xlim

3.1.设置标题、轴标签、刻度以及刻度标签

fig = plt.figure()
ax = fig.add_subplot(1,1,1) ax.plot(np.random.randn(1000).cumsum()) #改变X轴的刻度,最简单的方法是使用set_xticks和set_xticklabels。
#前者告诉刻度放在数据范围中的哪些位置,默认情况下,这些位置是刻度标签,可以用set_xticklabels设置。
a=ax.set_xticks([0,250,500,750,1000])
b=ax.set_xticklabels(['one','two','three','four','five'],rotation=30,fontsize='small') ax.set_xlabel('Stages') plt.show()

3.2.添加图例(legend)、注解以及在Subplot上绘图

两种方式,最简单的是在添加subplot的时候传入label参数

fig = plt.figure()
ax = fig.add_subplot(1,1,1) ax.plot(np.random.randn(1000).cumsum(), 'k', label='one')
ax.plot(np.random.randn(1000).cumsum(), 'k--', label='two')
ax.plot(np.random.randn(1000).cumsum(), 'k.', label='three') ax.legend(loc='best')
#loc表示将图例放在哪
#从图例中去除一个或多个元素,不传入label或label='_nolegend_'即可 #注解以及在Subplot上绘图
#注解可以通过text,arrow和annotate等函数进行添加。
#text可以将文本绘制在图标的指定坐标(x,y),还可以加上一些自定义格式
#ax.text(x ,y, 'Hello world!',family='monosapce',fontsize=10) plt.show()

3.3.将图表保存到文件

plt.savefig('filepath.svg')
plt.savefig('filepath.svg', dpi=400,bbox_inches='tight')

Figure.savefig参数

  • fname:路径,包含设置文件格式(如.pdf等)

  • dpi:图像分辨率,默认100

  • facecolor、edgecolor:图像背景色,默认为'w'(白色)

  • format:显示设置文件格式

  • bbox_inches:图像需要保存的部分。'tight',将尝试剪除图像周围的空白部分

Python Matplotlib绘图基础的更多相关文章

  1. python matplotlib 绘图基础

    在利用Python做数据分析时,探索数据以及结果展现上图表的应用是不可或缺的. 在Python中通常情况下都是用matplotlib模块进行图表制作. 先理下,matplotlib的结构原理: mat ...

  2. python之matplotlib绘图基础

    Python之matplotlib基础 matplotlib是Python优秀的数据可视化第三方库 matplotlib库的效果可参考 http://matplotlib.org/gallery.ht ...

  3. Python matplotlib绘图学习笔记

    测试环境: Jupyter QtConsole 4.2.1Python 3.6.1 1.  基本画线: 以下得出红蓝绿三色的点 import numpy as npimport matplotlib. ...

  4. Matplotlib绘图基础

    import matplotlib.pyplot as plt import numpy as np #绘图流程 x=np.linspace(-1,1,100) y=x**2 plt.plot(x,y ...

  5. 【划重点】Python matplotlib绘图建立画布和坐标系

    一.建立画布 import matplotlib.pyplot as plt import numpy as np x=np.arange(8) y=np.arange(8) print(x,y) # ...

  6. python matplotlib 绘图

    饼图 import matplotlib.pyplot as plt # The slices will be ordered and plotted counter-clockwise. label ...

  7. 吴裕雄 python matplotlib 绘图示例

    import matplotlib.pyplot as plt plt.scatter([1,2,3,4],[2,3,2,5])plt.title('My first plot')plt.show() ...

  8. python matplotlib绘图

    import numpy as np import matplotlib.pyplot as plt from scipy.constants.constants import alpha from ...

  9. python matplotlib 绘图 和 dpi对应关系

    dpi=1 600×400 dpi=2 1200×800 dpi=3 1800×1200 ........ dpi=21 (21×600)×(21×400) ---> 12600×8400 示例 ...

随机推荐

  1. 理解Linux的硬链接与软链接-转载

    理解Linux的硬链接与软链接 来自:https://www.ibm.com/developerworks/cn/linux/l-cn-hardandsymb-links/index.html

  2. JVM系列之:对象的锁状态和同步

    目录 简介 java对象头 java中锁状态的变化 偏向锁biased locking 轻量级锁thin lock 重量级锁 三种锁状态的不同 简介 锁和同步是java多线程编程中非常常见的使用场景. ...

  3. 第二节:Centos下安装Tomcat8.5.57

    Tomcat8.5.57安装(手动配置版) 建议官网直接下载(http://tomcat.apache.org/),我本次配置使用的版本 apache-tomcat-8.5.57.tar.gz. 1. ...

  4. Google免费新书-《构建安全&可靠的系统》

    前段时间riusksk在公众号分享的Google安全团队的新书,好书,全英原版,开源免费. 免费下载地址:https://static.googleusercontent.com/media/land ...

  5. spring boot 项目连接数据库查询数据过程

    spring boot 项目搭建 pom.xml <?xml version="1.0" encoding="UTF-8"?> <projec ...

  6. redis启动报错:The Windows version of Redis allocates a memory mapped heap for sharing with

    windows系统下通过cmd命令:redis-server.exe redis.windows.conf 启动redis报错,控制台报错如下: The Windows version of Redi ...

  7. react 阻止事件传递/冒泡

    当我们设计界面时,在以下情况会需要阻止元素/组件内的事件阻断,不被上层触发: 弹出提示框,期望点击框外空白区域可以关闭弹框.点击框内不关闭弹框 组件设计时,期望点击全局/点击指定元素时,显示不一样的交 ...

  8. acwing 173. 矩阵距离(bfs)

    给定一个N行M列的01矩阵A,A[i][j] 与 A[k][l] 之间的曼哈顿距离定义为: dist(A[i][j],A[k][l])=|i−k|+|j−l|dist(A[i][j],A[k][l]) ...

  9. npm ERR! Unexpected end of JSON input while

    rm -rf node_modules package-lock.json and npm cache clean --force solved it

  10. 如何查看Oracle的版本

    本人使用的软件是DataGrip 在控制台输入 select * from v$version;