【问题标题】:Long vertical bar plot with matplotlib使用 matplotlib 绘制长垂直条形图
【发布时间】:2018-12-19 09:49:59
【问题描述】:

我需要创建一个 Python 脚本,将(排序的)值列表绘制为垂直条形图。我想绘制所有值并将其保存为一个长垂直图,以便 yticks 标签和条形图都清晰可见。也就是说,我想要一个“长”的垂直图。列表中的元素数量各不相同(例如从 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')

如何修改脚本,以便可以垂直拉伸图形并使其可读?

【问题讨论】:

  • 您别无选择,只能更改图形大小。粗略估计,如果您有 n 个字体大小为 10 的标签并使用 100 的图形 dpi,则可以计算 n*10/0.72/100 并添加约 2 英寸。要进行更准确的计算,您需要考虑数字边距。

标签: python matplotlib plot bar-chart


【解决方案1】:

根据数据值的数量更改figsize。此外,相应地管理 y 轴限制。

以下工作完美:

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

下面是n=200的输出图片

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2020-02-28
    • 1970-01-01
    相关资源
    最近更新 更多