Chris90
Chris90

Reputation: 1998

I am getting an error when trying to plot a matplotlib scatter plot using for loop?

I am getting an error I cant seem to understand when im trying to plot a scatterplot below:

plt.figure(figsize=(8,6))
for i in range(0,df.shape[0]):
    plt.scatter(df['polarity'][i], df['subjectivity'][i], color = 'Blue' )

plt.title('Sentiment Analysis')
plt.xlabel('Polarity')
plt.ylabel('Subjectivity')
plt.show()

Where my polarity and subjectivity cols are number values

I get

KeyError:3  

 ----> 3     plt.scatter(df['polarity'][i], df['subjectivity'][i], color = 'Blue' )

not sure what I am missing here, any help appreciated, thanks!

Upvotes: 1

Views: 1153

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

df['polarity'][i] extract item at index i of the series df['polarity']. The error says df['polarity'] does not have an index 3, for example, df can look like

   polarity
0         1
1         2
2         3
4         1

Why don't you try:

plt.scatter(df['polarity'], df['subjectivity'], color='b')

Or:

df.plot.scatter(x='polarity', y='subjectivity')

Upvotes: 1

Related Questions