简体   繁体   中英

Long vertical bar plot with matplotlib

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 (eg 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?

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

t

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM