2

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:

AttributeError: 'PathCollection' object has no attribute '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()
gre_gor
  • 6,669
  • 9
  • 47
  • 52
Withoutahold
  • 31
  • 1
  • 2
  • 5
  • 1
    Possible duplicate of [How do I change the range of the x-axis with datetimes in MatPlotLib?](http://stackoverflow.com/questions/21423158/how-do-i-change-the-range-of-the-x-axis-with-datetimes-in-matplotlib) – Ilya V. Schurov Dec 21 '15 at 22:49

2 Answers2

4

You can create axes and then use 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)
Ilya V. Schurov
  • 7,687
  • 2
  • 40
  • 78
3

Use plt.xlim(min, max) instead.

Robert Pollak
  • 3,751
  • 4
  • 30
  • 54