How To Change Color Of Each Bar In Bar Plot And High Of Description Above Each Bar In Python Pandas Matplotlib?
I have DataFrame and bar plot in Pandas in Python like below: DF = pd.DataFrame({'Clients' : [10, 20, 30, 40]}, index = ['group1', 'group2', 'group3', 'group4']) ax = DF.plot.bar(
Solution 1:
To color the bars individually, you can directly use matplotlib's bar
plot instead of the pandas function.
To easily label bars, the latest matplotlib has a new function bar_label()
.
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({"Clients": [10, 20, 30, 40]},
index=["group1", "group2", "group3", "group4"])
fig, ax = plt.subplots(figsize=(17, 5))
bars = ax.bar(df.index, df['Clients'], color=["green", "red", "blue", "cyan"])
ax.set(ylim=(0, 50))
# ax.margins(y=0.1) # easier method to reserve some extra space
ax.bar_label(bars, size=15, color='red')
ax.grid(True)
plt.show()
PS: If, for some reason, you want to keep closer to your original code, you could set the bar color in the same loop that add the labels. In the original code, you can set the \n
at the end (f'{p.get_height()}\n'
) to obtain a better spacing.
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({"Clients": [10, 20, 30, 40]},
index=["group1", "group2", "group3", "group4"])
ax = df.plot.bar(figsize=(17, 5), grid=True, edgecolor='white', legend=False)
ax.set(ylim=(0, 50))
for p, color in zip(ax.patches, ["green", "red", "blue", "cyan"]):
p.set_facecolor(color)
ax.annotate(f'{p.get_height()}\n',
(p.get_x() + p.get_width() / 2,
p.get_height()),
ha="center",
va="center",
color="red",
size=15)
plt.tight_layout()
plt.show()
Post a Comment for "How To Change Color Of Each Bar In Bar Plot And High Of Description Above Each Bar In Python Pandas Matplotlib?"