【发布时间】:2021-09-18 01:32:41
【问题描述】:
我在绘制多个水平条形图的总 y 轴范围以使所有值相互对齐并仅使最左侧图上的 y 标签可见时遇到问题。 我有下面的数据框(数据),在开始创建图形和轴之前,我使用 pd.Grouper 函数按时间间隔分组。由于我使用数据框,我为我创建的每个轴分配了一个图。该代码未正确绘制值。如果我删除了 sharey=y,那么每个图都会正确显示,但当然不会与一个共同的 y 轴对齐。
import pandas as pd
import matplotlib.pyplot as plt
#group by time interval
data_gb = data.groupby([pd.Grouper(freq='1min')])
#create and set y-axis range limits from original dataframe
custom_ylim = (data.price.min(), data.price.max())
#number of plots based on number of intervals
numplot = len(data_gb)
# create a tuple of axe names seems like a hack
axes = tuple(['ax'+str(n) for n in range(1, numplot+1)])
f, axes = plt.subplots(1, numplot, sharey= True, sharex=True)
#iterate and assign plot to each axes
for (t, prices), ax in zip(data_gb, axes):
ax.set_ylim(custom_ylim) #this doesn't seem to do anything
prices.plot.barh('price', stacked=True, ax=ax)
ax.legend_ = None
plt.show()
timestamp price colA colB colC colD
2021-09-08 13:30:00+00:00 11.00 0.0 140037.0 0.0 0.0
2021-09-08 13:30:00+00:00 11.01 21963.0 34732.0 2961.0 1190.0
2021-09-08 13:30:00+00:00 11.02 17578.0 15434.0 12309.0 2.0
2021-09-08 13:30:00+00:00 11.03 2493.0 12393.0 11229.0 907.0
2021-09-08 13:30:00+00:00 11.04 17240.0 16406.0 1479.0 100.0
... ... ... ... ... ...
2021-09-08 13:31:00+00:00 11.01 8520.0 22579.0 4031.0 248.0
2021-09-08 13:31:00+00:00 11.02 64626.0 10330.0 11340.0 3862.0
2021-09-08 13:31:00+00:00 11.03 10967.0 5144.0 2621.0 640.0
2021-09-08 13:31:00+00:00 11.04 15168.0 2907.0 0.0 4.0
2021-09-08 13:31:00+00:00 11.05 1279.0 0.0 0.0 0.0
【问题讨论】:
-
是的,我已经删除了它并离开了 sharey,但它仍然无法正常工作。如果我删除 sharey,它们只会变成一系列独立的情节。我希望为所有图对齐 y 标签。
-
当我删除 ax.set_ylim(custom_ylim) 和 sharey = False 时,它看起来就像我发布的第二张图片。我正在使用 python 3.7 和 matplotlib 3.4..3
-
使用 sharey=True 并通过遍历轴来单独分配 ax.set_ylim(custom_ylim) 会完全搞砸。我正在使用熊猫 1.1.2。
-
您认为我还应该添加哪些信息来帮助解决问题?如果您愿意,我们可以将其移至聊天?
-
根据我发布的帖子,看起来第二个包含所有数据,但我想要一个包含整个价格高低的通用 y 轴,并且每个柱对齐. .
标签: python pandas matplotlib