X 轴散点图 Pandas MatplotLib 上的限制范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34404495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:24:59  来源:igfitidea点击:

Limit Range on X Axis Scatter Plot Pandas MatplotLib

pythonpandasmatplotlib

提问by Withoutahold

I have a dataframe that is indexed based on time, with another column indicating the number of injured pedestrians during a crash occuring at that hour. I am trying to use Matplotlib in order to graph the data, and have successfully graphed it, however, the range is much too large. I have data for one day, and would like to set the x axis limit accordingly using the min and max values calculted. I have tried using plt.set_xlim but I get an error:

我有一个基于时间索引的数据框,另一列表示当时发生撞车事故时受伤行人的数量。我正在尝试使用 Matplotlib 来绘制数据,并成功绘制了它,但是,范围太大了。我有一天的数据,并想使用计算的最小值和最大值相应地设置 x 轴限制。我曾尝试使用 plt.set_xlim 但出现错误:

AttributeError: 'PathCollection' object has no attribute 'set_xlim'

AttributeError: 'PathCollection' 对象没有属性 'set_xlim'

How can the limit be properly set?

如何正确设置限制?

Graph without limits
Graph without limits

图表无限制
图表无限制

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()

回答by Ilya V. Schurov

You can create axes and then use ax.xlim().

您可以创建轴,然后使用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)