基础环境:
1.python34
2.matplotlib1.4.3
3.win32
matplotlib基础练习一 plot()
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
效果
如上:若只赋予plot()一个参数,那么matplotlib会自动赋值给x轴,且从0开始,所以该图效果等同于:
plt.plot([0,1,2,3],[1,2,3,4])
例子:
plt.plot([0,1,2,3],[1,2,3,4],color='#254424',linestyle='dashed',label='line 1')
plt.plot([1,2,3],[1,4,9],'rs',label='line 2')
更多使用方法要查看帮助 : help(“matplotlib.pyplot.plot”)
matplotlib基础练习二 文字
在图标上增加文字,主要使用如下函数
- text() - add text at an arbitrary location to the Axes;matplotlib.axes.Axes.text() in the API.
- xlabel() - add an axis label to the x-axis;matplotlib.axes.Axes.set_xlabel() in the API.
- ylabel() - add an axis label to the y-axis;matplotlib.axes.Axes.set_ylabel() in the API.
- title() - add a title to the Axes; matplotlib.axes.Axes.set_title() in the API.
- figtext() - add text at an arbitrary location to the Figure; matplotlib.figure.Figure.text() in the API.
- suptitle() - add a title to the Figure; matplotlib.figure.Figure.suptitle() in the API.
- annotate() - add an annotation, with
optional arrow, to the Axes ; matplotlib.axes.Axes.annotate() in the API.
例:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
fig = plt.figure()
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})
ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
ax.text(0.95, 0.01, 'colored text in axes coords',
verticalalignment='bottom', horizontalalignment='right',
transform=ax.transAxes,
color='green', fontsize=15)
ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05))
ax.axis([0, 10, 0, 10])
plt.show()
效果如图:
matplotlib基础练习三 基本饼图
import matplotlib.pyplot as plt
labels = 'GreenApple', 'YellowApple', 'RedApple'
sizes = [40, 25, 35]
colors = ['yellowgreen', 'gold', '#ff2121',]
explode = (0, 0.1, 0)
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal')
plt.show()
效果:
matplotlib基础练习四-以时间为轴的图表
-
目录结构:
-date_demo.py
-aaa
- -aapl.csv
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker
r = mlab.csv2rec('aaa/aapl.csv')
r.sort()
r = r[-30:] # get the last 30 days
N = len(r)
ind = np.arange(N) # the evenly spaced plot indices
def format_date(x, pos=None):
thisind = np.clip(int(x+0.5), 0, N-1)
return r.date[thisind].strftime('%Y-%m-%d')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()
plt.show()