## Matplotlib for Python Developers

#### Getting Started with Matplotlib

In [2]: x = range(6)
In [3]: plt.plot(x, [xi**2 for xi in x])

In [3]: x = np.arange(1, 5)
In [4]: plt.plot(x, x*1.5, x, x*3.0, x, x/3.0)

Grid, axes, and labels

In [5]: plt.grid(True)

In [5]: plt.axis() # shows the current axis limits values
Out[5]: (1.0, 4.0, 0.0, 12.0)

In [6]: plt.axis([0, 5, -1, 13]) # set new axes limits

In [2]: plt.plot([1, 3, 2, 4])
In [3]: plt.xlabel('This is the X axis')
In [4]: plt.ylabel('This is the Y axis')

Titles and legends

In [2]: plt.plot([1, 3, 2, 4])
In [3]: plt.title('Simple plot')

In [3]: x = np.arange(1, 5)
In [4]: plt.plot(x, x*1.5, label='Normal')
In [5]: plt.plot(x, x*3.0, label='Fast')
In [6]: plt.plot(x, x/3.0, label='Slow')
In [7]: plt.legend()

legend(loc='upper left')

loc可以选取的值，其中best，是自动找到最好的位置

Saving plots to a file

plt.savefig('plot123.png')

In [1]: import matplotlib as mpl
In [2]: mpl.rcParams['figure.figsize']
Out[2]: [8.0, 6.0]
In [3]: mpl.rcParams['savefig.dpi']
Out[3]: 100

an 8x6 inches figure with 100 DPI results in an 800x600 pixels image，这就是默认值

In [4]: plt.savefig('plot123_2.png', dpi=200)

#### Decorate Graphs with Plot Styles

Markers and line styles

Marker就是指形成线的那些点

plot() supports an optional third argument that contains a format string for each pair of X, Y arguments in the form of:
plt.plot(X, Y, '<format>', ...)

plot通过第三个string参数可以用来指定，Colors，Line styles，Marker styles

Marker的style

In [3]: y = np.arange(1, 3, 0.3)
In [4]: plt.plot(y, 'cx--', y+1, 'mo:', y+2, 'kp-.');

Handling X and Y ticks

The arguments (in the form of lists) that we can pass to the function are:
• Locations of the ticks
• Labels to draw at these locations (if necessary)

In [2]: x = [5, 3, 7, 2, 4, 1]
In [3]: plt.plot(x);
In [4]: plt.xticks(range(len(x)), ['a', 'b', 'c', 'd', 'e', 'f']);
In [5]: plt.yticks(range(1, 8, 2));

#### Plot types

Histogram charts

In [3]: y = np.random.randn(1000)
In [4]: plt.hist(y);
In [5]: plt.show()

hist默认是分为10类，即bins=10， 上图就是把取值[-4,4]上的1000个随机数，分成10个bins，统计每个的数据个数

In [6]: plt.hist(y, 25);

Error bar charts

In [3]: x = np.arange(0, 4, 0.2)
In [4]: y = np.exp(-x)
In [5]: e1 = 0.1 * np.abs(np.random.randn(len(y)))
In [8]: e2 = 0.1 * np.abs(np.random.randn(len(y)))
In [9]: plt.errorbar(x, y, yerr=e1, xerr=e2, fmt='.-', capsize=0);

In [11]: plt.errorbar(x, y, yerr=[e1, e2], fmt='.-');

Bar charts

plt.bar([1, 2, 3], [3, 2, 5]);

In [3]: data1 = 10*np.random.rand(5)
In [4]: data2 = 10*np.random.rand(5)
In [5]: data3 = 10*np.random.rand(5)
In [6]: e2 = 0.5 * np.abs(np.random.randn(len(data2)))
In [7]: locs = np.arange(1, len(data1)+1)
In [8]: width = 0.27
In [9]: plt.bar(locs, data1, width=width);
In [10]: plt.bar(locs+width, data2, yerr=e2, width=width, color='red');
In [11]: plt.bar(locs+2*width, data3, width=width, color='green') ;
In [12]: plt.xticks(locs + width*1.5, locs);

Pie charts

In [2]: plt.figure(figsize=(3,3));
In [3]: x = [45, 35, 20]
In [4]: labels = ['Cats', 'Dogs', 'Fishes']
In [5]: plt.pie(x, labels=labels);

0表示不分离，越大表示离pie center越远，需要显式指定每个wedges的explode

In [2]: plt.figure(figsize=(3,3));
In [3]: x = [4, 9, 21, 55, 30, 18]
In [4]: labels = ['Swiss', 'Austria', 'Spain', 'Italy', 'France', 'Benelux']
In [5]: explode = [0.2, 0.1, 0, 0, 0.1, 0]
In [6]: plt.pie(x, labels=labels, explode=explode, autopct='%1.1f%%');

Scatter plots

In [3]: x = np.random.randn(1000)
In [4]: y = np.random.randn(1000)
In [5]: plt.scatter(x, y);

marker来指定点的形状

In [7]: size = 50*np.random.randn(1000)
In [8]: colors = np.random.rand(1000)
In [9]: plt.scatter(x, y, s=size, c=colors);

#### Text inside figure, annotations, and arrows

plt.text(x, y, text)

In [3]: x = np.arange(0, 2*np.pi, .01)
In [4]: y = np.sin(x)
In [5]: plt.plot(x, y);
In [6]: plt.text(0.1, -0.04, 'sin(0)=0');

annotate，便于增加注释

xy，需要添加注释的坐标
xytext，注释本身的坐标
arrowprops，箭头的类型和属性

In [2]: y = [13, 11, 13, 12, 13, 10, 30, 12, 11, 13, 12, 12, 12, 11,12]
In [3]: plt.plot(y);
In [4]: plt.ylim(ymax=35); 增大y的空间，否则注释放不下
In [5]: plt.annotate('this spot must really\nmean something',
xy=(6, 30), xytext=(8, 31.5), arrowprops=dict(facecolor='black', shrink=0.05));

In [2]: plt.axis([0, 10, 0, 20]);
In [3]: arrstyles = ['-', '->', '-[', '<-', '<->', 'fancy', 'simple','wedge']
In [4]: for i, style in enumerate(arrstyles):
plt.annotate(style, xytext=(1, 2+2*i), xy=(4, 1+2*i), arrowprops=dict(arrowstyle=style));

In [5]: connstyles=["arc", "arc,angleA=10,armA=30,rad=15", "arc3,rad=.2", "arc3,rad=-.2", "angle", "angle3"]
In [6]: for i, style in enumerate(connstyles):
plt.annotate("", xytext=(6, 2+2*i), xy=(8, 1+2*i), arrowprops=dict(arrowstyle='->', connectionstyle=style));

#### Subplots

fig = plt.figure()
ax = fig.add_subplot(111)

fig.add_subplot(numrows, numcols, fignum)
- numrows represents the number of rows of subplots to prepare
- numcols represents the number of columns of subplots to prepare
- fignum varies from 1 to numrows*numcols and specifies the current subplot (the one used now)

In [2]: fig = plt.figure()
In [3]: ax1 = fig.add_subplot(211)
In [4]: ax1.plot([1, 2, 3], [1, 2, 3]);
In [5]: ax2 = fig.add_subplot(212)
In [6]: ax2.plot([1, 2, 3], [3, 2, 1]);

#### Plotting dates

import matplotlib as mpl
In [7]: date2_1 = dt.datetime(2008, 9, 23)
In [8]: date2_2 = dt.datetime(2008, 10, 3)
In [9]: delta2 = dt.timedelta(days=1)
In [10]: dates2 = mpl.dates.drange(date2_1, date2_2, delta2)

In [11]: y2 = np.random.rand(len(dates2))
In [12]: ax2.plot_date(dates2, y2, linestyle='-');

In [13]: dateFmt = mpl.dates.DateFormatter('%Y-%m-%d')
In [14]: ax2.xaxis.set_major_formatter(dateFmt)

In [15]: daysLoc = mpl.dates.DayLocator()
In [16]: hoursLoc = mpl.dates.HourLocator(interval=6)
In [17]: ax2.xaxis.set_major_locator(daysLoc)
In [18]: ax2.xaxis.set_minor_locator(hoursLoc)

In [22]: date1_1 = dt.datetime(2008, 9, 23)
In [23]: date1_2 = dt.datetime(2009, 2, 16)
In [24]: delta1 = dt.timedelta(days=10)
In [25]: dates1 = mpl.dates.drange(date1_1, date1_2, delta1)
In [26]: y1 = np.random.rand(len(dates1))
In [27]: ax1.plot_date(dates1, y1, linestyle='-');

major的是Month，minor的是week

In [28]: monthsLoc = mpl.dates.MonthLocator()
In [29]: weeksLoc = mpl.dates.WeekdayLocator()
In [30]: ax1.xaxis.set_major_locator(monthsLoc)
In [31]: ax1.xaxis.set_minor_locator(weeksLoc)

In [32]: monthsFmt = mpl.dates.DateFormatter('%b')
In [33]: ax1.xaxis.set_major_formatter(monthsFmt)

#### Using LaTeX formatting

the start and the end of a mathtext string is $在python raw string需要r‘’，表示不转义 直接看例子， In [6]: ax.text(2, 8, r"$ \mu \alpha \tau \pi \lambda \omega \tau \lambda \iota \beta $"); In [7]: ax.text(2, 6, r"$ \lim_{x \rightarrow 0} \frac{1}{x} $"); In [8]: ax.text(2, 4, r"$ a \ \leq \ b \ \leq \ c \ \Rightarrow \ a \ \leq \ c$"); In [9]: ax.text(2, 2, r"$ \sum_{i=1}^{\infty}\ x_i^2$"); In [10]: ax.text(4, 8, r"$ \sin(0) = \cos(\frac{\pi}{2})$"); In [11]: ax.text(4, 6, r"$ \sqrt[3]{x} = \sqrt{y}$"); In [12]: ax.text(4, 4, r"$ \neg (a \wedge b) \Leftrightarrow \neg a \vee \neg b$"); In [13]: ax.text(4, 2, r"$ \int_a^b f(x)dx\$");

posted on 2014-08-19 20:43  fxjwind  阅读(...)  评论(...编辑  收藏

• 随笔 - 457
• 文章 - 0
• 评论 - 211