Reputation: 113
Using matplotlib (with Python), is it possible to set properties for all subplots on a figure at once?
I've created a figure with multiple subplots, and I currently have something like this:
import numpy as np
import matplotlib.pyplot as plt
listItems1 = np.arange(0, 100)
listItems8 = np.arange(0, 100)
listItems11 = np.arange(0, 100)
figure1 = plt.figure(1)
# First graph on Figure 1
graphA = figure1.add_subplot(2, 1, 1)
graphA.plot(listItems1, listItems8, label='Legend Title')
graphA.legend(loc='upper right', fontsize='10')
graphA.grid(True)
plt.xticks(range(0, len(listItems1) + 1, 36000), rotation='20', fontsize='7', color='white', ha='right')
plt.xlabel('Time')
plt.ylabel('Title Text')
# Second Graph on Figure 1
graphB = figure1.add_subplot(2, 1, 2)
graphB.plot(listItems1, listItems11, label='Legend Title')
graphB.legend(loc='upper right', fontsize='10')
graphB.grid(True)
plt.xticks(range(0, len(listItems1) + 1, 36000), rotation='20', fontsize='7', color='white', ha='right')
plt.xlabel('Time')
plt.ylabel('Title Text 2')
plt.show()
Question, is there a way to set any or all of those properties at once? I'm going to have 6 different subplots on one figure, and it's a bit tedious to keep copy/pasting the same "xticks" settings and "legend" settings over and over again.
Is there some kind of "figure1.legend(..." kind of thing?
Thanks. First post for me. Hello world! ;)
Upvotes: 6
Views: 4175
Reputation: 25954
If your subplots are actually sharing an axis/some axes, you may be interested in specifying the sharex=True
and/or sharey=True
kwargs to subplots
.
See John Hunter explaining more in this video. It can give your graph a much cleaner look and reduce code repetition.
Upvotes: 7
Reputation: 2058
I would suggest using a for
loop:
for grph in [graphA, graphB]:
grph.#edit features here
You can also structure the for
loop differently depending on how you want to do this, e.g.
graphAry = [graphA, graphB]
for ind in range(len(graphAry)):
grph = graphAry[ind]
grph.plot(listItems1, someList[ind])
#etc
The nice thing about subplots is that you can use a for
loop to plot them too!
for ind in range(6):
ax = subplot(6,1,ind)
#do all your plotting code once!
You'll have to think about how to organize the data you want to plot to make use of the indexing. Make sense?
Whenever I do multiple subplots I think about how to use a for
loop for them.
Upvotes: 2