matplotlib a aprendizagem guia de uso

referência

níveis

Superlativo: o matplotlib "ambiente estado-máquina". Veja os exemplos abaixo, a utilização de toda a função módulo plt de fazer as coisas, não use métodos e propriedades do objeto.

import matplotlib.pyplot as plt

plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4, 5, 6])


plt.figure(2)                # a second figure
plt.plot([4, 5, 6])          # creates a subplot(111) by default

plt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title

plt.show()

Um secundário: uma primeira camada de interface orientada por objectos. Neste ponto, o módulo de função plt só é usado para criar uma figura, eixos e outros objetos, e, em seguida, fazer as coisas diretamente com o objeto interface.

x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig, ax = plt.subplots()  
ax.plot(x, y)  # 使用ax的方法做事情
plt.show()

objetos

Alt

figura

Figura compreende uma pluralidade de eixos, que não pode ser um

  • figura múltipla, eixos
import matplotlib.pyplot as plt

plt.figure(1)                # the first figure
plt.subplot(211)             # the first subplot in the first figure
plt.plot([1, 2, 3])
plt.subplot(212)             # the second subplot in the first figure
plt.plot([4, 5, 6])


plt.figure(2)                # a second figure
plt.plot([4, 5, 6])          # creates a subplot(111) by default

plt.figure(1)                # figure 1 current; subplot(212) still current
plt.subplot(211)             # make subplot(211) in figure1 current
plt.title('Easy as 1, 2, 3') # subplot 211 title

plt.show()
  • Uma figura, não há eixos
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
# plt.plot([1,2,3])  # draw a line (now have an axes)
# plt.show()  # show the plot

machados

Um membro do alvo tem uma pluralidade de eixos objetos eixo (trama 2D há dois, são eixos x e y; trama 3D tem três)

import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.2)
y = np.sin(x)
fig, ax = plt.subplots()
fig.suptitle("basic math")
ax.plot(x, y, label='sin')  # 使用ax的方法做事情
ax.set_title('sin function')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_xlim(-1, 11)
ax.legend()
plt.show()

dados

De um modo preferido dados np.array, paládio, e pode ser np.matrix seguinte conversão

a = pandas.DataFrame(np.random.rand(4,5), columns = list('abcde'))
a_asarray = a.values

b = np.matrix([[1,2],[3,4]])
b_asarray = np.asarray(b)

mpl, plt e Pylab

matplotlib é um pacote, pyplot é um módulo sob matplotlib, pyplot recolha Pylab e Numpy formar um espaço de nomes unificado (preterido é).

Para plt, a função da qual não é sempre um número actual e os eixos correntes (criado automaticamente)

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()

estilo de código

  • Np plt e reutilização explicitamente importação, nem todos os objetos introduzidos nele, para evitar a contaminação namespace
  • Uso plt criar eixos e a Figura objectos, e, em seguida, utilizar um método de controlo objecto adicional
  • Np fazer uso de dados
  • imagem de exibição Use plt
# 导入方式
import matplotlib.pyplot as plt
import numpy as np

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, (ax1, ax2) = plt.subplots(1, 2) # 获取figure和axes对象
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})
plt.show()

backend

Interativo e não-interativo back-end back-end

Especifique o backend

  1. backend arquivo de parâmetros matplotlibrc (meu computador, este arquivo está localizado em
    C: \ Users \ xxxx \ PycharmProjects \ untitled1 \ venv \ Lib \ site-packages \ matplotlib \ sob mpl-dados)
    Aqui Insert Picture Descrição
  2. Especificado no roteiro
import matplotlib
matplotlib.use('PS')   # generate postscript output by default

Neste ponto, se houver roteiro plt.show () não exibir as imagens, e será UserWarning relatou:
Aqui Insert Picture Descrição

  1. variável ambiente (que não há exemplos específicos)

considerações sobre o desempenho

O principal simplificação é o render, que compreende uma linha, marca, etc, pode ser usado como modo rápido, simples

import matplotlib.style as mplstyle
mplstyle.use('fast')
Publicado 135 artigos originais · ganhou elogios 7 · vê 30000 +

Acho que você gosta

Origin blog.csdn.net/math_computer/article/details/103646840
Recomendado
Clasificación