I haven't been able to find a solution to this.. Say I define some plotting function so that I don't have to copy-paste tons of code every time I make similar plots...
What I'd like to do is use this function to create a few different plots individually and then put them together as subplots into one figure. Is this even possible? I've tried the following but it just returns blanks:
import numpy as np import matplotlib.pyplot as plt # function to make boxplots def make_boxplots(box_data): fig, ax = plt.subplots() box = ax.boxplot(box_data) #plt.show() return ax # make some data: data_1 = np.random.normal(0,1,500) data_2 = np.random.normal(0,1.1,500) # plot it box1 = make_boxplots(box_data=data_1) box2 = make_boxplots(box_data=data_2) plt.close('all') fig, ax = plt.subplots(2) ax[0] = box1 ax[1] = box2 plt.show()
In Matplotlib, we can draw multiple graphs in a single plot in two ways. One is by using subplot() function and other by superimposition of second graph on the first i.e, all graphs will appear on the same plot.
subplot() function in Python. subplot() function adds subplot to a current figure at the specified grid position.
I tend to use the following template
def plot_something(data, ax=None, **kwargs): ax = ax or plt.gca() # Do some cool data transformations... return ax.boxplot(data, **kwargs)
Then you can experiment with your plotting function by simply calling plot_something(my_data)
and you can specify which axes to use like so.
fig, (ax1, ax2) = plt.subplots(2) plot_something(data1, ax1, color='blue') plot_something(data2, ax2, color='red')
Adding the kwargs
allows you to pass in arbitrary parameters to the plotting function such as labels, line styles, or colours.
The line ax = ax or plt.gca()
uses the axes you have specified or gets the current axes from matplotlib (which may be new axes if you haven't created any yet).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With