Issue
I want to show the value of the bar chart on the top of the bar chart. I using DataFrame for that. This is my code:
import matplotlib.pyplot as plt
import pandas as pd
from decimal import Decimal
data = {
'L': [86.0, 91.7, 92.3, 92.8],
'D': [87.6, 90.5, 91.1, 91.1],
'K': [87.0, 91.5, 92.5, 92.0],
'N': [84.0, 84.9, 91.7, 89.9],
'S': [91.0, 87.0, 88.8, 91.0]
}
barWidth = 0.9
colours = {"L": "#837E7C", "D": "#98F99F", "K": "#FFE24A", "N": "#E8ADAA", "S": "#87C0FF" }
df = pd.DataFrame(data,columns=['L','D', 'K', 'N', 'S'], index=['a', 'b', 'c', 'd'],)
df.plot.barh(figsize=(4,8), color=colours, fontsize = 14)
plt.ylabel('Type', fontsize = 14)
plt.yticks(rotation=90, ha="center", rotation_mode='anchor')
plt.label('Result', fontsize = 14)
plt.show()
and out is:
[![enter image description here][1]][1]
But did not show value on top. How to do it, using my code.
Solution
Is the following what you want? You need a workaround to iterate your multibar chart. The first step is to define an ax
object. The second step is to use a for
loop to get the values of each
bar.
import matplotlib.pyplot as plt
import pandas as pd
from decimal import Decimal
data = {
'L': [86.0, 91.7, 92.3, 92.8],
'D': [87.6, 90.5, 91.1, 91.1],
'K': [87.0, 91.5, 92.5, 92.0],
'N': [84.0, 84.9, 91.7, 89.9],
'S': [91.0, 87.0, 88.8, 91.0]
}
barWidth = 0.9
colours = {"L": "#837E7C", "D": "#98F99F", "K": "#FFE24A", "N": "#E8ADAA", "S": "#87C0FF" }
df = pd.DataFrame(data,columns=['L','D', 'K', 'N', 'S'], index=['a', 'b', 'c', 'd'])
ax = df.plot.barh(figsize=(4,8), color=colours, fontsize = 14)
for p in ax.patches:
ax.annotate(str(p.get_width()), (p.get_x() + p.get_width(), p.get_y()), xytext=(1, 2), textcoords='offset points')
plt.ylabel('Type', fontsize = 14)
plt.yticks(rotation=90, ha="center", rotation_mode='anchor')
plt.show()
Answered By - Ka-Wa Yip
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.