Matplotlib¶
Conceitos iniciais e exemplo básico:
- Figure é toda a figura - gráfico, títulos, anotações.
- Axes é uma região com área de plotagem. E uma Figure pode conter um ou mais Axes.
In [ ]:
Copied!
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots() # Criando uma figura com um Axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plotando os dados na área de plotagem do Axes.
plt.show() # Exibir a figura.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots() # Criando uma figura com um Axes.
ax.plot([1, 2, 3, 4], [1, 4, 2, 3]) # Plotando os dados na área de plotagem do Axes.
plt.show() # Exibir a figura.
Quando se está trabalhando com matplotlib tem-se dois estilos de codificar. Pode ser orientado a objeto ou o que a biblioteca chama de pyplot styles.
Orientado a objeto é como o exemplo inicial, onde se cria a Figure e os Axes e utiliza os métodos destes objetos. No método pyplot usa-se apenas as funções da biblioteca.
Seguem dois exemplos que tem o mesmo resultado, usando orientação a objetos e usando o pyplot:
In [ ]:
Copied!
# Orientação a Objetos
x = np.linspace(0, 2, 100) # Sample data.
# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(x, x, label='linear') # Plot some data on the Axes.
ax.plot(x, x**2, label='quadratic') # Plot more data on the Axes...
ax.plot(x, x**3, label='cubic') # ... and some more.
ax.set_xlabel('x label') # Add an x-label to the Axes.
ax.set_ylabel('y label') # Add a y-label to the Axes.
ax.set_title("Simple Plot") # Add a title to the Axes.
ax.legend() # Add a legend.
# Orientação a Objetos
x = np.linspace(0, 2, 100) # Sample data.
# Note that even in the OO-style, we use `.pyplot.figure` to create the Figure.
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(x, x, label='linear') # Plot some data on the Axes.
ax.plot(x, x**2, label='quadratic') # Plot more data on the Axes...
ax.plot(x, x**3, label='cubic') # ... and some more.
ax.set_xlabel('x label') # Add an x-label to the Axes.
ax.set_ylabel('y label') # Add a y-label to the Axes.
ax.set_title("Simple Plot") # Add a title to the Axes.
ax.legend() # Add a legend.
Out[ ]:
<matplotlib.legend.Legend at 0x177184a8ad0>
In [ ]:
Copied!
# Pyplot style
x = np.linspace(0, 2, 100) # Sample data.
plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear') # Plot some data on the (implicit) Axes.
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()
# Pyplot style
x = np.linspace(0, 2, 100) # Sample data.
plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear') # Plot some data on the (implicit) Axes.
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()
Out[ ]:
<matplotlib.legend.Legend at 0x177186156d0>
Caso precise criar vários gráficos, a biblioteca sugere usar a seguinte função abaixo para:
In [4]:
Copied!
def my_plotter(ax, data1, data2, param_dict):
"""
A helper function to make a graph.
"""
out = ax.plot(data1, data2, **param_dict)
return out
data1, data2, data3, data4 = np.random.randn(4, 100) # make 4 random data sets
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7))
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})
def my_plotter(ax, data1, data2, param_dict):
"""
A helper function to make a graph.
"""
out = ax.plot(data1, data2, **param_dict)
return out
data1, data2, data3, data4 = np.random.randn(4, 100) # make 4 random data sets
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7))
my_plotter(ax1, data1, data2, {'marker': 'x'})
my_plotter(ax2, data3, data4, {'marker': 'o'})
Out[4]:
[<matplotlib.lines.Line2D at 0x177184a6990>]
Estilos que podem ser aplicados:
In [9]:
Copied!
# Estilo das linhas
fig, ax = plt.subplots(figsize=(5, 2.7))
x = np.arange(len(data1))
ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='--') # atribuido diretamente na função plot
l, = ax.plot(x, np.cumsum(data2), color='orange', linewidth=2) # ou atribuído via objeto
l.set_linestyle(':') # retornado pela função plot.
# Estilo das linhas
fig, ax = plt.subplots(figsize=(5, 2.7))
x = np.arange(len(data1))
ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='--') # atribuido diretamente na função plot
l, = ax.plot(x, np.cumsum(data2), color='orange', linewidth=2) # ou atribuído via objeto
l.set_linestyle(':') # retornado pela função plot.
In [ ]:
Copied!
# Cores
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter(data1, data2, s=50, facecolor='C5', edgecolor='g')
# Cores
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter(data1, data2, s=50, facecolor='C5', edgecolor='g')
Out[ ]:
<matplotlib.collections.PathCollection at 0x1771a899450>
Patch¶
In [1]:
Copied!
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots()
# Add a rectangle patch
rect = patches.Rectangle((0.1, 0.1), 0.4, 0.3, linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
# Add a circle patch
circle = patches.Circle((0.7, 0.6), 0.2, linewidth=2, edgecolor='b', facecolor='g', alpha=0.5)
ax.add_patch(circle)
# Adjust axis limits to ensure patches are visible
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots()
# Add a rectangle patch
rect = patches.Rectangle((0.1, 0.1), 0.4, 0.3, linewidth=1, edgecolor='r', facecolor='none')
ax.add_patch(rect)
# Add a circle patch
circle = patches.Circle((0.7, 0.6), 0.2, linewidth=2, edgecolor='b', facecolor='g', alpha=0.5)
ax.add_patch(circle)
# Adjust axis limits to ensure patches are visible
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.show()