简体   繁体   English

使用matplotlib的长垂直条形图

[英]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. 我需要创建一个Python脚本,将(排序的)值列表绘制为垂直条形图。 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. 我想绘制所有值并将其保存为较长的垂直图,以便yticks标签和条都清晰可见。 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. 列表中的元素数量有所不同(例如,从500到1000),因此使用figsize并没有帮助,因为我不知道应该多长时间。

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. 根据数据值的数量更改figsize Also, manage the y-axis limit accordingly. 另外,相应地管理y轴限制。

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 下面给出的是n=200的输出图片

t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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