matplotlib 学习笔记(之一)

基本绘图

# If running headless, use a suitable GUI-less plotting backend
if not os.environ.get('DISPLAY'):
    import matplotlib
    matplotlib.use("Agg", force=True)

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

只提供一个list给plot函数时,matplotlib会将它当作y值对待,并自动将x值设为 0 ~ (len(y)-1)。

对于每一对x,y 参数,都有一个可选的参数,可以规定图标的形状和颜色。

plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()

调整线条属性

线条有多种属性:宽度、形状、抗锯齿……参考lines2D。多种设置属性的方法:

  • 关键词参数
plt.plot(x, y, linewidth=2.0)
  • 用 set 方法
line, = plt.plot(x, y, '-')
line.set_antialiased(False) # turn off antialising
  • 使用 setp() 命令
lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value 
pairsplt.setp(lines, 'color', 'r', 'linewidth', 2.0)

Working with multiple figures and axes

MATLAB 和 pyplot 都有 *当前图形 * 和 *当前坐标轴 * 的概念。所有绘图命令都作用于当前坐标轴。gca()函数返回当前坐标轴(一个matplotlib.axes.Axes实例),gcf()函数返回当前图形(matplotlib.figure.Figure实例)。

import numpy as np
import matplotlib.pyplot as plt
def f(t):
    return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()

此处figure()函数是可选的,因为figure(1)是默认执行的,如同不制定坐标轴时,subplot(111)是默认创建一样。subplot()函数制定numrows, numcols, figure,其中figure的顺序为1到numrowsnumcols*。

Working with text

text() 命令可以在任意位置添加文本,而 xlabel(),ylabel(),title()只能作用于特定位置。

import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

# the histogram of the data
n,bins,patches=plt.hist(x,50,normed=1,facecolor='g',alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()

Customizing plots with style sheets

通过style 包可以很容易的切换多种画图风格。

  • ggplot
import matplotlib.pyplot as plt
plt.style.use('ggplot')
  • 列出可用的style:
print(plt.style.available)

Saving plots to a file

plt.plot([1,2,3])
plt.savefig('test.png')

文件格式由扩展名决定。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python画图之总结待整理 https://morvanzhou.github.io/tutorials/dat...
    jiandanjinxin阅读 17,414评论 1 14
  • 艺术家教程 原文:Artist tutorial 译者:飞龙 协议:CC BY-NC-SA 4.0 matplot...
    布客飞龙阅读 3,590评论 0 11
  • 按:plot,figure,Axes这些名词很烦,不尝试翻译了。 Ipython Notebook比较适合演示ma...
    mhye阅读 7,057评论 1 8
  • (1)小白兔蹦蹦跳跳到面包房,问:“老板,你们有没有一百个小面包啊?” 老板:“啊,真抱歉,没有那么多” “这样啊...
    顔先生阅读 496评论 0 1
  • 白天,心里像涌起了千层蚂蚁窝一般,很想在蓝天白云与风和日丽间奔跑,于是便浩浩荡荡地出门了,但开始就吃了闭门羹,理想...
    realtear阅读 294评论 0 1