我有一个基于时间索引的数据框,另一列表示在该小时发生的车祸中受伤的行人数量。我正在尝试使用 Matplotlib 来绘制数据图形,并已成功绘制图形,但是,范围太大了。我有一天的数据,想使用计算出的最小值和最大值相应地设置 x 轴限制。我尝试使用 plt.set_xlim 但出现错误:
AttributeError: 'PathCollection' object has no attribute 'set_xlim'
如何正确设置限制?
df = test_request_pandas()
df1 = df[['time','number_of_pedestrians_injured']]
df1.set_index(['time'],inplace=True)
df1 = df1.astype(float)
min = df1.index.min()
max = df1.index.max()
fig = plt.scatter(df1.index.to_pydatetime(), df1['number_of_pedestrians_injured'])
#fig.set_xlim([min, max]) // causing me issues
plt.show()
请您参考如下方法:
您可以创建轴,然后使用 ax.xlim()。
import pandas as pd
df = pd.DataFrame({'x':[1,2,3], 'y':[3,4,5]})
fig = plt.figure()
ax = plt.subplot(111)
df.plot(x='x',y='y',ax=ax, kind='scatter')
ax.set_xlim(2,3)
