Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
931 views
in Technique[技术] by (71.8m points)

python - Scatter plot form dataframe with index on x-axis

I've got pandas DataFrame, df, with index named date and the columns columnA, columnB and columnC

I am trying to scatter plot index on a x-axis and columnA on a y-axis using the DataFrame syntax.

When I try:

df.plot(kind='scatter', x='date', y='columnA')

I ma getting an error KeyError: 'date' probably because the date is not column

df.plot(kind='scatter', y='columnA')

I am getting an error:

ValueError: scatter requires and x and y column

so no default index on x-axis.

df.plot(kind='scatter', x=df.index, y='columnA')

I am getting error

KeyError: "DatetimeIndex(['1818-01-01', '1818-01-02', '1818-01-03', '1818-01-04',

                          '1818-01-05', '1818-01-06', '1818-01-07', '1818-01-08',

                          '1818-01-09', '1818-01-10',
               ...
  
                          '2018-03-22', '2018-03-23', '2018-03-24', '2018-03-25',

                          '2018-03-26', '2018-03-27', '2018-03-28', '2018-03-29',
 
                          '2018-03-30', '2018-03-31'],
  
dtype='datetime64[ns]', name='date', length=73139, freq=None) not in index"

I can plot it if I use matplotlib.pyplot directly

plt.scatter(df.index, df['columnA'])

Is there a way to plot index as x-axis using the DataFrame kind syntax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is kind of ugly (I think the matplotlib solution you used in your question is better, FWIW), but you can always create a temporary DataFrame with the index as a column usinng

df.reset_index()

If the index was nameless, the default name will be 'index'. Assuming this is the case, you could use

df.reset_index().plot(kind='scatter', x='index', y='columnA')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...