Kabilesh
Kabilesh

Reputation: 1012

How to plot average in y axis for each x value in pyplot

I am using matplotlib.pyplot to visualize my data. In pandas I have columns 'hour' and 'favourite_count'. hour has values form 0 to 24. favourite_count is a continuous variable. What I want is to plot a bar chart which visualizes the average favourite_count for each hour. Currently I am plotting a basic graph as below. In the y axis this plots the sum / maximum of favourite_count for each hour (I am not sure which). How can I plot a graph that visualizes hour vs average_favorite_count_for_hour

plt.bar(result['hour'], result['favourite_count'])
plt.xlabel('hour')
plt.ylabel('favourite_count')
plt.title('hour vs popularity', y=1.1)
plt.grid()
plt.show()

Upvotes: 4

Views: 19175

Answers (1)

user10795172
user10795172

Reputation:

Perform an averaging step by adding this line just before plotting:

result = result.groupby('hour').mean()

then plot as below:

plt.bar(result.index, result['favourite_count'])
plt.xlabel('hour')
plt.ylabel('favourite_count')
plt.title('hour vs popularity', y=1.1)
plt.grid()
plt.show()

Note the x axis is now the index.

Upvotes: 5

Related Questions