I created a bar chart and would like to place the count value above each bar.
# Import the libraries
import pandas as pd
from matplotlib import pyplot as plt
# Create the DataFrame
df = pd.DataFrame({
'city_code':[1200013, 1200104, 1200138, 1200179, 1200203],
'index':['good', 'bad', 'good', 'good', 'bad']
})
# Plot the graph
df['index'].value_counts().plot(kind='bar', color='darkcyan',
figsize=[15,10])
plt.xticks(rotation=0, horizontalalignment="center", fontsize=14)
plt.ylabel("cities", fontsize=16)
I'm getting the following result
I would like to add the values at the top of each bar. The values of the count I got from value_counts. Something like this:
Thanks to everyone who helps.
Example using patches
and annotate
:
# Import the libraries
import pandas as pd
from matplotlib import pyplot as plt
# Create the DataFrame
df = pd.DataFrame(
{
"city_code": [1200013, 1200104, 1200138, 1200179, 1200203],
"index": ["good", "bad", "good", "good", "bad"],
}
)
# Plot the graph
ax = df["index"].value_counts().plot(kind="bar", color="darkcyan", figsize=[15, 10])
plt.xticks(rotation=0, horizontalalignment="center", fontsize=14)
plt.ylabel("cities", fontsize=16)
for p in ax.patches:
ax.annotate(
str(p.get_height()), xy=(p.get_x() + 0.25, p.get_height() + 0.1), fontsize=20
)
plt.savefig("test.png")
Result: