Matplotlib में लीजेंड निर्माण को स्वचालित करने के लिए, हम निम्नलिखित चरण ले सकते हैं:
- फिगर आकार सेट करें और सबप्लॉट के बीच और आसपास पैडिंग समायोजित करें।
- नमूना डेटा की संख्या के लिए एक चर, N, आरंभ करें।
- numpy का उपयोग करके x, y, c और s डेटा बनाएं।
- subplots() मेथड का उपयोग करके एक फिगर और सबप्लॉट का सेट बनाएं।
- विभिन्न रंगों और आकारों के साथ x और y डेटा बिंदु प्लॉट करें। <ली>अक्ष पर लीजेंड रखें।ली>
- फिगर में एक आर्टिस्ट जोड़ें।
- PathCollection के लिए लीजेंड हैंडल और लेबल बनाएं।
- आकारों के लिए फिर से अक्ष पर लीजेंड रखें।
- फिगर प्रदर्शित करने के लिए show() मेथड का उपयोग करें।
उदाहरण
import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True N = 45 x, y = np.random.rand(2, N) c = np.random.randint(1, 5, size=N) s = np.random.randint(10, 220, size=N) fig, ax = plt.subplots() scatter = ax.scatter(x, y, c=c, s=s) legend1 = ax.legend(*scatter.legend_elements(), loc="lower left", title="Classes") ax.add_artist(legend1) handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6) legend2 = ax.legend(handles, labels, loc="upper right", title="Sizes") plt.show()
आउटपुट
