matplotlib 入门之Usage Guide

matplotlib教程学习笔记

Usage Guide

import matplotlib.pyploy as plt
import numpy as np

parts of figure

Figure: Axes, title, figure legends等的融合体?

fig = plt.figure()  # an empty figure with no axes
fig.suptitle('No axes on this figure')  # Add a title so we know which it is

fig, ax_lst = plt.subplots(2, 2)  # a figure with a 2x2 grid of Axes

image.png

Axes: 通常意义上的可视化数据的图,一个figure可以拥有许多Axes. 难道是,一个figure上可以画不同数据的图,每种图就是一个Axes?

Axis: 大概就是通常意义的坐标轴了吧。

Artist: 基本上我们所见所闻都是Artist,标题,线等等。与Axes绑定的Artist不能共享。

plotting函数的输入

最好的ndarray类型,其他对象如pandas, np.matrix等可能会产生错误。

matplotlib, pyplot, pylab, 三者的联系

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

plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')

plt.xlabel('x label')
plt.ylabel('y label')

plt.title("Simple Plot")

plt.legend() #图例

plt.show()

image.png

第一次使用plt.plot,函数会自动创建figure和axes,之后再使用plt.plot,会重复使用当前的figure和axes,新建的artist也会自动地使用当前地axes。

pylab好像把plt.plot和numpy统一起来了,但是会造成名称的混乱而不推荐使用。

Coding style

pyplot style, 在程序开头应当:

import matplotlib.pyplot as plt
import numpy as np

数据+创建figures+使用对象方法:

x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()

image.png

当面对不同的数据的时候,往往需要设计一个函数来应对,建议采取下面的设计格式:

def my_plotter(ax, data1, data2, param_dict):
    """
    A helper function to make a graph

    Parameters
    ----------
    ax : Axes
        The axes to draw to

    data1 : array
       The x data

    data2 : array
       The y data

    param_dict : dict
       Dictionary of kwargs to pass to ax.plot

    Returns
    -------
    out : list
        list of artists added
    """
    out = ax.plot(data1, data2, **param_dict)
    return out

# which you would then use as:

data1, data2, data3, data4 = np.random.randn(4, 100)
fig, ax = plt.subplots(1, 1) #一个plot
my_plotter(ax, data1, data2, {'marker': 'x'})

image.png

fig, (ax1, ax2) = plt.subplots(1, 2) #2-plots
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})

image.png

Backends 后端

不太明白。
后面的就不看了。

猜你喜欢

转载自www.cnblogs.com/MTandHJ/p/10804591.html
今日推荐