I would like to know how can I label multiple matplotlib charts, please?
If I call .xlabel(), or .ylabel() on plt directly only one of the graphs gets labelled, however if I call the functions on the figure, I get an error.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(19680801)
N_points = 100000
dist1 = rng.standard_normal(N_points)
fig1 = plt.figure()
axis = fig1.add_subplot(1,1,1)
axis.grid()
fig2 = plt.figure()
ax = fig2.add_subplot(1,1,1)
ax.grid()
plt.xlabel('X AXIS')
plt.ylabel('Y AXIS')
axis.hist(dist1)
ax.hist(dist1)
plt.show()
CodePudding user response:
You can set the labels using the Axes (axis and ax in you case) with the set_xlabel and set_ylabel methods. E.g.,
# add labels onto the first plot
axis.set_xlabel("X AXIS")
axis.set_ylabel("X AXIS")
...
ax.set_xlabel("Another X AXIS")
ax.set_ylabel("Another X AXIS")
Note that you're currently also creating two separate figures. If you want two plots on the same figure you could do:
fig, ax = plt.subplots(2, 1)
Then ax[0] will be the first axis onto which you can plot and ax[1] will be the second.
