Matplotlib returns a plot object

I have a function that wraps pyplot.plt, so I can quickly create graphs with commonly used default values:

def plot_signal(time, signal, title='', xlab='', ylab='',
                line_width=1, alpha=1, color='k',
                subplots=False, show_grid=True, fig_size=(10, 5)):

    # Skipping a lot of other complexity here

    f, axarr = plt.subplots(figsize=fig_size)
    axarr.plot(time, signal, linewidth=line_width,
               alpha=alpha, color=color)
    axarr.set_xlim(min(time), max(time))
    axarr.set_xlabel(xlab)
    axarr.set_ylabel(ylab)
    axarr.grid(show_grid)

    plt.suptitle(title, size=16)
    plt.show()

However, there are times when I want to return the plot to manually add / edit things for a specific schedule. For example, I want to be able to change axis labels or add a second line to the graph after calling the function:

import numpy as np

x = np.random.rand(100)
y = np.random.rand(100)

plot = plot_signal(np.arange(len(x)), x)

plot.plt(y, 'r')
plot.show()

I saw several questions on this question ( How to return the matplotlib.figure.Figure object from the Pandas function of the graph function? And AttributeError: the 'Figure' object does not have the 'plot' attribute ), and as a result I tried to add the following at the end of the function:

  • return axarr

  • return axarr.get_figure()

  • return plt.axes()

However, they all return a similar error: AttributeError: 'AxesSubplot' object has no attribute 'plt'

, ?

+4
1

, . , pyplot.plt . plt pyplot , .. import matplotlib.pyplot as plt.

, return axarr . .

def plot_signal(x,y, ..., **kwargs):
    # Skipping a lot of other complexity her
    f, ax = plt.subplots(figsize=fig_size)
    ax.plot(x,y, ...)
    # further stuff
    return ax

ax = plot_signal(x,y, ...)
ax.plot(x2, y2, ...)
plt.show()
+2

Source: https://habr.com/ru/post/1676961/


All Articles