Issue
I need to plot 1 large plot at the top of a figure, and then a small plot UNDERNEATH it. Currently I have this code:
times = [1, 2, 3, 4]
temps1 = [1, 2, 3, 4]
temps2 = [10, 20, 30, 40]
temps3 = [100, 200, 300, 400]
plt.subplot(211)
plt.plot(times, temps1, c="#ff7f0e", label="1")
plt.plot(times, temps2, c="#2ca02c", label="2")
plt.plot(times, temps3, c="#1f77b4", label="3")
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
width = 0.35 # the width of the bars: can also be len(x) sequence
plt.subplot(212)
plt.bar(labels, men_means, width, label='Men')
plt.bar(labels, women_means, width, bottom=men_means,
label='Women')
plt.show()
and this correctly plots the graphs underneath eachother. However, I can't set the size of the second figure (the one underneath) I need it to not be the same size as the other, and I have tried many variations such as changing it to fig,ax = ..
and then changing the fig, this didn't work and many other variations. There are some that work with plots next to eachother but not underneath. How can I independently change the size of each of these plots?
Solution
I'm not sure if the size of each graph is what you want, so I created them in the appropriate ratio.' Use 'GridSpec()' to determine the number of graphs in rows and columns, and specify the row ratio and column ratio as parameters. Once the placement is determined, associate the graphs to it.Kindly refer to this.
import matplotlib.pyplot as plt
times = [1, 2, 3, 4]
temps1 = [1, 2, 3, 4]
temps2 = [10, 20, 30, 40]
temps3 = [100, 200, 300, 400]
fig = plt.figure(figsize=(10, 8))
gs = plt.GridSpec(nrows=2, ncols=1, height_ratios=[3, 1])
ax1 = fig.add_subplot(gs[0, 0])
ax1.plot(times, temps1, c="#ff7f0e", label="1")
ax1.plot(times, temps2, c="#2ca02c", label="2")
ax1.plot(times, temps3, c="#1f77b4", label="3")
labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
width = 0.35
ax2 = fig.add_subplot(gs[1, 0])
ax2.bar(labels, men_means, width, label='Men')
ax2.bar(labels, women_means, width, bottom=men_means, label='Women')
plt.show()
Answered By - r-beginners
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.