可根据列的高度进行调整的可变 Y 轴

Variable Y-Axis That Adjusts to the Height of the columns

我正在寻找当前设置的 y 轴限制的快速代码,如下所示

# Set the Y Axis Limits
ax.set_ylim(0,100)

我希望根据我们的数据点将 100 换成 variable/adjustable y 水平,如下所示:

import pandas as pd
import matplotlib.pyplot as plt

s = pd.Series(
[8, 24, 21, 23, 24],
index = ["Your Plan", "Benchmark", "Region", "Industry", "Size"]
)

我想这应该是一个快速修复。

您必须根据数据系列的最小值和最大值设置 y 轴限制,这些值是 numpy.max 和 numpy.min 的结果:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

s = pd.Series(
[8, 24, 21, 23, 24],
index = ["Your Plan", "Benchmark", "Region", "Industry", "Size"]
)

plt.plot(s.values)
ax = plt.gca()
ax.set_ylim(np.min(s),np.max(s))
plt.show()

如果删除或不使用行ax.set_ylim(0,100),限制将自动调整到数据。

如果要固定轴的一端而让另一端自动调整,也可以使用

ax.set_ylim(0,None)

如果添加到代码 plt.gca().autoscale_view(),您可以自动缩放坐标轴。它允许自动调整当前轴限制以适应数据。