Matplotlib returning a plot object

2024/11/20 15:21:22

I have a function that wraps pyplot.plt so I can quickly create graphs with oft-used defaults:

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 heref, 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 where I'd want to be able to return the plot so I can manually add/edit things for a specific graph. For example, I want to be able to change the axis labels, or add a second line to the plot after calling the function:

import numpy as npx = np.random.rand(100)
y = np.random.rand(100)plot = plot_signal(np.arange(len(x)), x)plot.plt(y, 'r')
plot.show()

I've seen a few questions on this (How to return a matplotlib.figure.Figure object from Pandas plot function? and AttributeError: 'Figure' object has no attribute 'plot') and as a result I've tried adding the following to 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'

Whats the correct way to return a plot object so it can be edited later?

Answer

I think the error is pretty self-explanatory. There is no such thing as pyplot.plt, or similar. plt is the quasi-standard abbreviated form of pyplot when being imported, i.e., import matplotlib.pyplot as plt.

Concerning the problem, the first approach, return axarr is the most versatile one. You get an axis, or an array of axes, and can plot to it.

The code may look like:

def plot_signal(x,y, ..., **kwargs):# Skipping a lot of other complexity heref, ax = plt.subplots(figsize=fig_size)ax.plot(x,y, ...)# further stuffreturn axax = plot_signal(x,y, ...)
ax.plot(x2, y2, ...)
plt.show()
https://en.xdnf.cn/q/26307.html

Related Q&A

Where is the history file for ipython

I can not determine where the ipython is storing its history.a. There is no ~/.pythonhistory:12:49:00/dashboards $ll ~/.py* ls: /Users/steve/.py*: No such file or directoryb. Nothing special in the pyt…

How do I find what is using memory in a Python process in a production system?

My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. Ive used a Python memory profiler (specifically, Heapy) with some success in th…

In Django is there a way to display choices as checkboxes?

In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this:APPROVAL_CHOICES = ((yes, Yes),(no, No),(cancelled, Cancelled), )client_app…

How to get the first 2 letters of a string in Python?

Lets say I have a string str1 = "TN 81 NZ 0025" two = first2(str1) print(two) # -> TNHow do I get the first two letters of this string? I need the first2 function for this.

Python sqlite3 version

Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >…

Python debugger (pdb) stopped handlying up/down arrows, shows ^[[A instead

I am using python 2.6 in a virtualenv on an Ubuntu Linux 11.04 (natty) machine. I have this code in my (django) python code:import pdb ; pdb.set_trace()in order to launch the python debugger (pdb).Up u…

Un-persisting all dataframes in (py)spark

I am a spark application with several points where I would like to persist the current state. This is usually after a large step, or caching a state that I would like to use multiple times. It appears …

Can pip (or setuptools, distribute etc...) list the license used by each installed package?

Im trying to audit a Python project with a large number of dependencies and while I can manually look up each projects homepage/license terms, it seems like most OSS packages should already contain the…

Convert DataFrameGroupBy object to DataFrame pandas

I had a dataframe and did a groupby in FIPS and summed the groups that worked fine.kl = ks.groupby(FIPS)kl.aggregate(np.sum)I just want a normal Dataframe back but I have a pandas.core.groupby.DataFram…

Correct way to obtain confidence interval with scipy

I have a 1-dimensional array of data:a = np.array([1,2,3,4,4,4,5,5,5,5,4,4,4,6,7,8])for which I want to obtain the 68% confidence interval (ie: the 1 sigma).The first comment in this answer states that…