美文网首页Matplotlib
python使用matplotlib可视化

python使用matplotlib可视化

作者: 何同尘 | 来源:发表于2019-01-31 23:16 被阅读14次

导入matplotlib

import matplotlib as mpl
import matplotlib.pyplot as plt

设置样式
plt.style.use('classic')

show()在什么时候用

在脚本文件里绘图 需要使用plt.show()

# ------- file: myplot.py ------
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)

plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))

plt.show()

$ python myplot.py

在ipython命令行里绘图

In [1]: %matplotlib
Using matplotlib backend: TkAgg

In [2]: import matplotlib.pyplot as plt

在笔记本里绘图
%matplotlib notebook
will lead to interactive plots embedded within the notebook
%matplotlib inline
will lead to static images of your plot embedded in the notebook

存储图片到文件

fig.savefig('my_figure.png')
#查看所有的图片
from IPython.display import Image
Image('my_figure.png')

绘画线形

%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np

fig = plt.figure()
ax = plt.axes()
x = np.linspace(0, 10, 1000)
ax.plot(x, np.sin(x));
plt.plot(x, np.sin(x));

#调整线形和颜色
plt.plot(x, np.sin(x - 0), color='blue')        # specify color by name
plt.plot(x, np.sin(x - 1), color='g')           # short color code (rgbcmyk)
plt.plot(x, np.sin(x - 2), color='0.75')        # Grayscale between 0 and 1
plt.plot(x, x + 0, linestyle='solid')
plt.plot(x, x + 1, linestyle='dashed')
plt.plot(x, x + 4, linestyle='-')  # solid
plt.plot(x, x + 5, linestyle='--') # dashed
plt.plot(x, x + 6, linestyle='-.') # dashdot
plt.plot(x, x + 7, linestyle=':');  # dotted
plt.plot(x, x + 0, '-g')  # solid green
plt.plot(x, x + 1, '--c') # dashed cyan

#调整轴
plt.xlim(-1, 11)
plt.ylim(-1.5, 1.5);
plt.axis('tight');

#增加标签
plt.title("A Sine Curve")
plt.xlabel("x")
plt.ylabel("sin(x)");

#也可以同时设置
ax = plt.axes()
ax.plot(x, np.sin(x))
ax.set(xlim=(0, 10), ylim=(-2, 2),
       xlabel='x', ylabel='sin(x)',
       title='A Simple Plot');

简单的散点图

%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np

x = np.linspace(0, 10, 30)
y = np.sin(x)

plt.plot(x, y, 'o', color='black');
plt.scatter(x, y, marker='o');

错误可视化

离散偏差

%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as np

x = np.linspace(0, 10, 50)
dy = 0.8
y = np.sin(x) + dy * np.random.randn(50)

plt.errorbar(x, y, yerr=dy, fmt='.k');

连续差

plt.plot(xdata, ydata, 'or')
plt.plot(xfit, yfit, '-', color='gray')

plt.fill_between(xfit, yfit - dyfit, yfit + dyfit,
                 color='gray', alpha=0.2)
plt.xlim(0, 10);

密度图和等高线图

%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np

x = np.linspace(0, 5, 50)
y = np.linspace(0, 5, 40)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.contour(X, Y, Z, colors='black');
plt.contour(X, Y, Z, 20, cmap='RdGy');
plt.contourf(X, Y, Z, 20, cmap='RdGy')
plt.colorbar();

#类似于matlab contourf imshow 

直方图,密度图,条形图

plt.hist(data);
plt.hist(data, bins=30, normed=True, alpha=0.5,
         histtype='stepfilled', color='steelblue',
         edgecolor='none');
#分幅
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)
kwargs = dict(histtype='stepfilled', alpha=0.3, normed=True, bins=40)

plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs)
plt.hist(x3, **kwargs);

二维直方图

plt.hist2d(x, y, bins=30, cmap='Blues')
counts, xedges, yedges = np.histogram2d(x, y, bins=30)

六边形图

plt.hexbin(x, y, gridsize=30, cmap='Blues')
cb = plt.colorbar(label='count in bin')

核密度图

定制标注

x = np.linspace(0, 10, 1000)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), '-b', label='Sine')
ax.plot(x, np.cos(x), '--r', label='Cosine')
ax.axis('equal')
leg = ax.legend();
#调整位置
ax.legend(loc='upper left', frameon=False)
fig
#标注分为两列
ax.legend(frameon=False, loc='lower center', ncol=2)
fig

#给标注增加一个背景,有边缘阴影
ax.legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)
fig

#更多请查看帮助

定制颜色条

plt.colorbar();
plt.imshow(I, cmap='gray');

cmap的色系
viridis
cubehelix
RdBu
jet

多个子图绘制

%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
#不同的水平轴
ax1 = plt.axes()  # standard axes
ax2 = plt.axes([0.65, 0.65, 0.2, 0.2])

#通过在图上增加水平坐标轴分幅
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4],
                   xticklabels=[], ylim=(-1.2, 1.2))
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.4],
                   ylim=(-1.2, 1.2))

x = np.linspace(0, 10)
ax1.plot(np.sin(x))
ax2.plot(np.cos(x));
image.png image.png

plt.subplot 简单的分图

for i in range(1, 7):
    plt.subplot(2, 3, i)
    plt.text(0.5, 0.5, str((2, 3, i)),
             fontsize=18, ha='center')
#一个图一个图的增加
fig = plt.figure()
fig.subplots_adjust(hspace=0.4, wspace=0.4)
for i in range(1, 7):
    ax = fig.add_subplot(2, 3, i)
    ax.text(0.5, 0.5, str((2, 3, i)),
           fontsize=18, ha='center')

plt.subplots 里整个分图在一个坐标

fig, ax = plt.subplots(2, 3, sharex='col', sharey='row')
![image.png](https://img.haomeiwen.com/i14391893/0066147cccccdb32.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

plt.GridSpec: More Complicated

grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)

image.png

文本和注释

ax.text('2012-1-1', 3950, "New Year's Day", **style)
# transform=ax.transData is the default, but we'll specify it anyway
ax.text(1, 5, ". Data: (1, 5)", transform=ax.transData)
ax.text(0.5, 0.1, ". Axes: (0.5, 0.1)", transform=ax.transAxes)
ax.text(0.2, 0.2, ". Figure: (0.2, 0.2)", transform=fig.transFigure

箭头和注释

%matplotlib inline

fig, ax = plt.subplots()

x = np.linspace(0, 20, 1000)
ax.plot(x, np.cos(x))
ax.axis('equal')

ax.annotate('local maximum', xy=(6.28, 1), xytext=(10, 4),
            arrowprops=dict(facecolor='black', shrink=0.05))

ax.annotate('local minimum', xy=(5 * np.pi, -1), xytext=(2, -6),
            arrowprops=dict(arrowstyle="->",
                            connectionstyle="angle3,angleA=0,angleB=-90"));

设置刻度

#放缩
ax = plt.axes(xscale='log', yscale='log')
#隐藏刻度
ax.yaxis.set_major_locator(plt.NullLocator())
ax.xaxis.set_major_formatter(plt.NullFormatter())
#增加或者减小刻度数量
axi.xaxis.set_major_locator(plt.MaxNLocator(3))
    axi.yaxis.set_major_locator(plt.MaxNLocator(3))

#其他刻度格式
ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2))
![image.png](https://img.haomeiwen.com/i14391893/abbf6d7f1b440631.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

其他知识

Summary of Formatters and Locators

We've mentioned a couple of the available formatters and locators.
We'll conclude this section by briefly listing all the built-in locator and formatter options. For more information on any of these, refer to the docstrings or to the Matplotlib online documentaion.
Each of the following is available in the plt namespace:

Locator class Description
NullLocator No ticks
FixedLocator Tick locations are fixed
IndexLocator Locator for index plots (e.g., where x = range(len(y)))
LinearLocator Evenly spaced ticks from min to max
LogLocator Logarithmically ticks from min to max
MultipleLocator Ticks and range are a multiple of base
MaxNLocator Finds up to a max number of ticks at nice locations
AutoLocator (Default.) MaxNLocator with simple defaults.
AutoMinorLocator Locator for minor ticks
Formatter Class Description
NullFormatter No labels on the ticks
IndexFormatter Set the strings from a list of labels
FixedFormatter Set the strings manually for the labels
FuncFormatter User-defined function sets the labels
FormatStrFormatter Use a format string for each value
ScalarFormatter (Default.) Formatter for scalar values
LogFormatter Default formatter for log axes

We'll see further examples of these through the remainder of the book.

配置和样式

plt.rc 的意思就是 configuration配置的意思。
调整样式:

#可获得的样式
plt.style.available[:5]
#使用某种样式
with plt.style.context('stylename'):
    make_a_plot()
with plt.style.context('ggplot'):
    hist_and_lines()
with plt.style.context('bmh'):
    hist_and_lines()
with plt.style.context('dark_background'):
    hist_and_lines()
with plt.style.context('grayscale'):
    hist_and_lines()
import seaborn
hist_and_lines()

相关文章

网友评论

    本文标题:python使用matplotlib可视化

    本文链接:https://www.haomeiwen.com/subject/tiilsqtx.html