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

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

7 Comments

@IIya V. Schurov What does the 111 mean?
It creates a "subfigure matrix" with 1 row and 1 column. See details here: stackoverflow.com/questions/3584805/…
@IIya V. Schurov I get "KeyError:time"
Using the command: df1.plot(x='time',y='number_of_pedestrians_injured', kind='scatter')
You can still use plt.scatter instead of df1.plot as you do. For example, you can try plt.xlim() instead of fig.set_xlim() in your code.
|
3

Use plt.xlim(min, max) instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.