Reputation: 3821
I need to create a Python script that plots a list of (sorted) value as a vertical bar plot. I'd like to plot all the values and save it as a long vertical plot, so that both the yticks labels and bars are clearly visible. That is, I'd like a "long" verticalplot. The number of elements in the list varies (e.g. from 500 to 1000), so the use of figsize
does not help as I don't know how long that should be.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
# Example data
n = 500
y_pos = np.arange(n)
performance = 3 + 10 * np.random.rand(n)
ax.barh(y_pos, np.sort(performance), align='center', color='green', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels([str(x) for x in y_pos])
ax.set_xlabel('X')
How can I modify the script so that I can stretch the figure vertically and make it readable?
Upvotes: 1
Views: 1563
Reputation: 3967
Change the figsize
depending on the number of data values. Also, manage the y-axis limit accordingly.
The following works perfectly:
n = 500
fig, ax = plt.subplots(figsize=(5,n//5)) # Changing figsize depending upon data
# Example data
y_pos = np.arange(n)
performance = 3 + 10 * np.random.rand(n)
ax.barh(y_pos, np.sort(performance), align='center', color='green', ecolor='black')
ax.set_yticks(y_pos)
ax.set_yticklabels([str(x) for x in y_pos])
ax.set_xlabel('X')
ax.set_ylim(0, n) # Manage y-axis properly
Given below is the output picture for n=200
Upvotes: 4