-1

I want to draw 7 or 8 Histogram (share x axis) dynamically in one figure using Python. But the figure only show part of it. enter image description here Although it has 7 subplots: enter image description here Here is my codes:

import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
import pickle
distribution = pickle.load(open("data.txt", "r"))
fig,axes = plt.subplots(nrows = len(distribution), sharex = True)
index=0
for tag in distribution_progress:
    axes[index].hist(distribution_[tag],bins=50, normed=1, facecolor='yellowgreen', alpha=0.75)
    axes[index].set_title(tag)
    index += 1
plt. subplots_adjust( top = 3, hspace = 0.4)
plt.show()
Pingjiang Li
  • 727
  • 1
  • 12
  • 27
  • 2
    I'm confused. What is the problem? Which graph is produced? – DavidG Jan 15 '18 at 11:55
  • 2
    `top = 3` means that the content of the figure is 300% larger than the figure itself. Hence only its bottom part is shown. The second picture seems to be the desired outcome so it's unclear what the question really is here. – ImportanceOfBeingErnest Jan 15 '18 at 12:03

1 Answers1

1

Specify a figure size with a larger height/width ratio:

width, height = 6, 8
fig,axes = plt.subplots(nrows=N, sharex=True, figsize=(width, height))

Increase the hspace to provide enough room for the subplot titles:

plt. subplots_adjust(hspace = 1.0)

As ImportanceOfBeingErnest pointed out, don't use top = 3 since that places the top of the subplots at y = 3 in the Figure coordinate system, whereas the top of the visible figure is always at y = 1 (in the Figure coordinate system).


import numpy as np
import matplotlib.pyplot as plt
N = 8
width, height = 6, 8
fig, axes = plt.subplots(nrows=N, sharex=True, figsize=(width, height))
index = 0
for tag in range(N):
    axes[index].hist(np.random.random(100), bins=50, normed=1,
                     facecolor='yellowgreen', alpha=0.75)
    axes[index].set_title(tag)
    index += 1
plt. subplots_adjust(hspace=1.0)
plt.show()

enter image description here

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Thanks for your answer! If I understand correctly, the subplots share the figure, and the figure's max size is limited. So I cannot enlarge the height of each of the 7 charts, otherwise it is exceeded the boundary of figure? – Pingjiang Li Jan 16 '18 at 03:35
  • @PingjiangLi: Yes, that's basically right. [`plt.subplots_adjust`](https://matplotlib.org/devdocs/api/_as_gen/matplotlib.pyplot.subplots_adjust.html) changes spacing parameters. It does not enlarge axes. It only changes their position within the figure. See [this post](https://stackoverflow.com/a/14846126/190597) for more on matplotlib's hierarchy of objects. – unutbu Jan 16 '18 at 12:20