Matplotlib में मल्टीपल लेबल्स के साथ बार चार्ट प्लॉट करने के लिए निम्नलिखित चरणों का पालन करें:
चरण
- men_means, men_std, women_means और women_std के लिए डेटासेट बनाएं।
- NumPy का उपयोग करके इंडेक्स डेटा पॉइंट्स बनाएं।
- बार्स की width इनिशियलाइज़ करें।
- subplots() मेथड का उपयोग करके फिगर और सबप्लॉट्स का सेट बनाएं।
- bar() मेथड का उपयोग करके rects1 और rects2 बार्स रेक्टेंगल बनाएं।
- set_ylabel(), set_title(), set_xticks() और set_xticklabels() मेथड्स का उपयोग करें।
- प्लॉट पर लीजेंड रखें।
- autolabel() मेथड का उपयोग करके बार चार्ट के लिए मल्टीपल लेबल्स जोड़ें।
- फिगर डिस्प्ले करने के लिए show() मेथड का उपयोग करें।
उदाहरण
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)
ind = np.arange(len(men_means))
width = 0.35
fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std, label='Men')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std, label='Women')
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()
def autolabel(rects, xpos='center'):
ha = {'center': 'center', 'right': 'left', 'left': 'right'}
offset = {'center': 0, 'right': 1, 'left': -1}
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(offset[xpos]*3, 3),
textcoords="offset points",
ha=ha[xpos], va='bottom')
autolabel(rects1, "left")
autolabel(rects2, "right")
plt.show()
आउटपुट
ग्रुप्ड बार चार्ट दिखाई देगा जिसमें पुरुष और महिला के बार्स अगल-बगल होंगे, प्रत्येक बार पर मान लेबल होगा।