Matplotlib isn’t only for static plots. While GUIs are typically created with GUI libraries and frameworks such as پی کیو ٹی, ٹکنٹر, کیوی اور wxPython، اور جب کہ Python کا PyQt، Tkinter کے ساتھ بہترین انضمام ہے۔ اور wxPython – there’s no need to use any of these for some basic GUI functionality, through Matplotlib وجیٹس.
۔ matplotlib.widgets
ماڈیول کی کئی کلاسیں ہیں، بشمول AxesWidget
جس میں سے Button
s, CheckButton
s, Slider
s, TextBox
es، وغیرہ اخذ کیے گئے ہیں۔ یہ سب قبول کرتے ہیں۔ Axes
they’re being added to as the one and only mandatory constructor argument, and their positioning has to be manually set. A thing to note is that the ویجیٹ محور ہے, so you’ll create an Axes
ہر ویجیٹ کے لیے مثال۔
ایک اور بات قابل غور ہے کہ آپ کو ویجٹ کے حوالے رکھنا ہوں گے۔ بصورت دیگر، وہ کوڑا کرکٹ جمع کر سکتے ہیں۔
ان میں سے ہر ایک کو ترتیب دے کر بھی غیر فعال کیا جا سکتا ہے۔ active
کرنے کے لئے False
, in which case, they won’t respond to any events, such as being clicked on. That being said, we can introduce a new type of interactivity to our plots, through various GUI elements and components.
نوٹ: Matplotlib isn’t meant to be used for high-quality GUI creation, nor user-friendly systems. These widgets are rudimentary, don’t really look great and have limited functionality. They’re meant as a way to prototype and test things out, rather than actually ship them.
If you’ve worked with PyQt before – you might notice that the general syntax and approach to adding these widgets, as well as connecting them to event handlers is fairly familiar.
بٹن شامل کرنا
کے ساتھ شروع کرتے ہیں بٹن - matplotlib.widgets
ماڈیول کی وضاحت کرتا ہے a Button
کلاس اس سے منسلک ہونے کے لیے، ہم کال کریں۔ on_clicked()
فنکشن، جو ہمارے فراہم کردہ فنکشن کو انجام دیتا ہے۔ ایک بار جب ایک کلک کا پتہ چل جاتا ہے، فنکشن عمل میں آتا ہے۔
بٹن بناتے وقت، ہم ایک تفویض کرتے ہیں۔ Axes
اس کے لیے، پوزیشننگ کے لیے استعمال کیا جاتا ہے۔ ہم ایک میں بھی گزر سکتے ہیں۔ label
اس وقت، کچھ متن شامل کرنے اور اسے صارف کے لیے تشریح کرنے کے لیے۔ دی color
اور hovercolor
arguments define the color of the button before and after it’s being hovered over.
Since we take care of the positioning and space for all widgets – let’s create a Figure
اور Axes
, allow for some spacing at the bottom to add a button, and plot an empty Scatter Plot. Then, we’ll define an EventHandler
کلاس، جس کا ایک ہی طریقہ ہے۔ add_random()
. یہ طریقہ دو بے ترتیب نمبر تیار کرتا ہے، اور ان کے لیے ایک مارکر پر پلاٹ کرتا ہے۔ Axes
we’ve created before and calls plt.draw()
، جو دوبارہ کھینچتا ہے۔ Figure
. When updating plots, we’ll always have to call plt.draw()
دوبارہ اصل میں اسے اپ ڈیٹ کرنے کے لیے:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
plot = ax.scatter([], []) class EventHandler: def add_random(self, event): x = np.random.randint(0, 100) y = np.random.randint(0, 100) ax.scatter(x, y) plt.draw() # Axes for the Button and positioning
# xposition and yposition in percentages, width, height
button_ax = plt.axes([0.7, 0.05, 0.2, 0.07])
# Create Button and assign it to `button_ax` with label
button = Button(button_ax, 'Add Random', color='green', hovercolor='red')
# On a detected click, execute add_random()
button.on_clicked(EventHandler().add_random) plt.show()
اس کے نتیجے میں a Figure
، ایک خالی کے ساتھ Axes
اس کے اندر اور اسکرین کے اوپری دائیں کونے پر ایک بٹن، خود ہی Axes
:
اور بٹن کو ایک دو درجن بار دبانے کے بعد، ہمارا ax
بے ترتیب مارکر کے ساتھ آباد کیا جائے گا:
مزید عملی اصطلاحات میں، ہم ایک بنا سکتے ہیں۔ سائیکل ہر بٹن دبانے پر پلاٹ کرنے کی خصوصیات۔ اس کے لیے چند ٹویکس کی ضرورت ہے۔ EventHandler
کے ساتھ ساتھ اس چکر میں واپس جانے کے لیے ایک اور بٹن۔
آئیے استعمال کریں۔ ریڈ وائن کا معیار ڈیٹاسیٹ کو دوبارہ، اور اس کے خلاف کئی خصوصیات کا تصور کریں۔ شراب feature. Since we can’t be bothered to plot these individually by writing the code to plot one feature against the other, and then modifying that code to plot another feature against the other.
Creating a Scatter Matrix might help us here, but if the dataset has a lot of features, it’ll be fairly unreadable and we won’t get far. If you’d like to have دونوں بڑے پیمانے پر پلاٹ جو آپ آسانی سے دیکھ اور تشریح کر سکتے ہیں، اس کے ساتھ ساتھ as having multiple features cycling through without any extra effort – you can automate this process with buttons:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import Button fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2) df = pd.read_csv('winequality-red.csv')
plot = ax.scatter([], []) class EventHandler: i = 0 # Find and plot next feature, re-draw the Axes def next_feature(self, event): # If the counter is at the end of the columns # Revert it back to 0 to cycle through again if self.i >= len(df.columns): self.i = 0 # Clear Axes from last plot ax.cla() # Plot a feature against a feature located on the `i` column ax.scatter(df['alcohol'], df.iloc[:,self.i]) # Set labels ax.set_xlabel('Alcohol') ax.set_ylabel(df.columns[self.i]) # Increment i self.i += 1 # Update Figure plt.draw() def previous_feature(self, event): # If the counter is at the start of the columns # Revert it back to the last column to cycle through if self.i <= 0: self.i = len(df.columns)-1 ax.cla() ax.scatter(df['alcohol'], df.iloc[:,self.i]) ax.set_xlabel('Alcohol') ax.set_ylabel(df.columns[self.i]) self.i -= 1 plt.draw() # Add buttons
button1_ax = plt.axes([0.7, 0.02, 0.2, 0.07])
next_button = Button(button1_ax, 'Next Feature')
next_button.on_clicked(EventHandler().next_feature) button2_ax = plt.axes([0.45, 0.02, 0.2, 0.07])
previous_button = Button(button2_ax, 'Previous Feature')
previous_button.on_clicked(EventHandler().previous_feature) plt.show()
۔ EventHandler
class now has two methods – next_feature()
اور previous_feature()
. یہ دونوں چیک کریں کہ آیا کاؤنٹر i
has reached the end or start of the column list – and to avoid an IndexError
، ہم انڈیکس کو مخالف قدر پر دوبارہ ترتیب دیتے ہیں اور a کی نقل کرتے ہیں۔ سائیکل. نیچے جا رہے ہیں۔ 0
ہمیں واپس لے جائے گا آخر کالم کی فہرست میں، اور آخری کالم کے اوپر جانے سے ہمیں واپس پہلے کی طرف لے جایا جائے گا۔
After ascertaining where we’re located – we صاف کریں Axes
, since we’d be plotting again on top of an existing plot without clearing it via cla()
(clکان axes)۔ آپ متبادل طور پر ایک دوسرے کے اوپر پلاٹ بنا کر خصوصیت کے تعلقات کو بھی جمع کر سکتے ہیں اور استعمال کر سکتے ہیں۔ cla()
سائیکل کے اختتام/شروع میں انڈیکس کو ری سیٹ کرتے وقت بیان۔
صاف کرنے کے بعد Axes
– we’ve got a cleared canvas to paint on with the ax.scatter()
فنکشن اس مثال میں، فکسڈ خصوصیت ہے شراب, so it’s present at all times. The other feature varies, and can be accessed through iloc[]
، کالم کے انڈیکس میں گزر رہا ہے۔ یہ واپسی a Series
جسے ہم اس پلاٹ میں استعمال کر سکتے ہیں۔ اسی طرح، ہم تک رسائی حاصل کر سکتے ہیں کالم کے نام through their index as well – df.columns[index]
، جو Y-axis لیبل سیٹ کرنے کے لیے استعمال ہوتا ہے۔
آخر میں، ہم کاؤنٹر اور کال کو بڑھاتے/کم کرتے ہیں۔ plt.draw()
کو اپ ڈیٹ کرنے کے لیے۔ Figure
:
ایک بار جب ہم پر کلک کریں۔ اگلی خصوصیت بٹن، کالموں کی فہرست میں اگلی خصوصیت کے خلاف سازش کی جائے گی۔ شراب، اور Figure
will be appropriately updated – the labels, markers and scale. The same goes the other way around – پچھلی خصوصیت فہرست کو مخالف سمت میں طے کرے گا، ہمیں ایک حفاظتی طریقہ کار کے ساتھ سائیکل چلانے کی اجازت دیتا ہے جو ہر بار جب ہم سائیکل کے اختتام یا آغاز پر پہنچتے ہیں تو ہمارے کاؤنٹر کو دوبارہ ترتیب دیتا ہے۔
ریڈیو بٹن اور چیک باکسز شامل کرنا
ریڈیو بٹن۔ صارف کو منتخب کرنے کی اجازت دینے کے لیے استعمال کیا جاتا ہے۔ ایک قدر باہر کا کئی اقدار. ایک وقت میں صرف ایک ریڈیو بٹن منتخب کیا جا سکتا ہے، اور وہ عام طور پر کسی انتخاب کی نمائندگی کرتے ہیں۔ چیک باکسز can be used if you’d like to let the user select multiple options at once.
نوٹ: چیک باکس ہے یا نہیں یہ چیک کرنے کی بہت محدود صلاحیت ہے۔ on or بند. In fact, there’s none out of the box. You can only ever check if the box is دباؤ or نوٹ، جو اس کے استعمال کے بارے میں ایک سنگین حد پیدا کرتا ہے کیونکہ ہمیں کوئی اندازہ نہیں ہے کہ یہ اس سے پہلے کس حالت میں تھا۔ واحد متبادل یہ ہے کہ بولین کے ساتھ باکس کی موجودہ حالت کے بارے میں اپنا کاؤنٹر/چیک رکھیں، اور اس کی بنیاد پر منطق کو تبدیل کریں۔
یہ آپ کو، مثال کے طور پر، ہر ایک کے لیے ایک چیک باکس شامل کرنے کی اجازت دے گا۔ حسب ضرورت دلیل ایک خاص پلاٹ کا، صارف کو انہیں سیٹ کرنے کی اجازت دیتا ہے۔ True
or False
(چیک شدہ، یا غیر چیک شدہ)، یا ان ریاستوں پر مبنی کوئی دوسری غیر متضاد میپنگ۔
Though, since the API is limited itself, we’ll limit ourselves to the intended usage as well – turning things on and off. We’ll have two features, that we can turn on اور بند via a Checkbox. Note that even this functionality is limited to objects for which you can check if they’re visible or not.
On the other hand, we don’t want to allow the user to apply two scales at once, or to set two X-limits at once, since only the statement called second in the sequence would be applied. For these – we’d use Radio Buttons.
Let’s add a couple of Radio Buttons to let the user select the axis range via a couple of Radio Buttons, but also allow them turn feature visualizations on اور بند:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
from matplotlib.widgets import RadioButtons fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2) df = pd.read_csv('winequality-red.csv') # Plot two line plots for two features, and turn them invisible
line1, = ax.plot(df['fixed acidity'], visible=False)
line2, = ax.plot(df['citric acid'], visible=False) class EventHandler: # set_range handler def set_range(label): if (label == 'Small Range'): ax.set_xlim(0, 1600) ax.set_ylim(0, 25) else: ax.set_xlim(0, 1600) ax.set_ylim(0, 50) plt.draw() # Turn off, if on, and on if off def apply_features(label): if (label == 'Fixed Acidity'): line1.set_visible(not line1.get_visible()) elif (label == 'Citric Acid'): line2.set_visible(not line2.get_visible()) plt.draw() # Add radio buttons and checkboxes
ranges_ax = plt.axes([0.7, 0.02, 0.2, 0.1])
range_radio_buttons = RadioButtons(ranges_ax, ('Small Range', 'Large Range'))
range_radio_buttons.on_clicked(EventHandler.set_range) checkboxes_ax = plt.axes([0.4, 0.02, 0.25, 0.1])
checkboxes = CheckButtons(checkboxes_ax, ('Fixed Acidity', 'Citric Acid'))
checkboxes.on_clicked(EventHandler.apply_features) plt.show()
Again, we’ve got two methods in the EventHandler()
کلاس - set_range()
اور apply_features()
. set_range()
method sets the range to either “small” or “large”, by adjusting the Axes
‘ X and Y-limits. The apply_features()
فنکشن کو تبدیل کرتا ہے۔ visible
لائن پلاٹس کا فیلڈ جو ہم نے پہلے بنایا تھا، ان کے موجودہ کی بنیاد پر visible
حالت. اگر visible == True
، ہم لائن پلاٹ کو بند کر دیتے ہیں، اور اس کے برعکس۔
We have to rely on the built-in ability to check the visibility of Line Plots, since we can’t check if the checkbox was checked or not before. This same ability can be emulated with a status
کے دائرہ کار میں بولین EventHandler()
کلاس، جس پر سیٹ ہے۔ True
اور False
on every click, for plot types that don’t support checking if they’re visible out of the box.
اس کوڈ کو چلانے کے نتیجے میں a Figure
نیچے بٹنوں کے دو سیٹ کے ساتھ۔ اگر ہم دونوں چیک باکسز کو چیک کرتے ہیں تو دونوں لائن پلاٹ ظاہر ہوں گے:
ہم انہیں انفرادی طور پر بند کر سکتے ہیں:
اور ہم کی حد کو تبدیل کر سکتے ہیں Axes
ریڈیو بٹن کے ذریعے:
ٹیکسٹ باکسز کو شامل کرنا
ٹیکسٹ بکس کے عادی ہیں جمع data from the user – and we can alter the plots based on this data. For example, we can ask a user to input the name of a feature, or to insert a function for our plot to visualize. Of course, working with user input can be tricky – there are always edge cases to look out for.
Let’s write a script that allows the user to input a خصوصیت کا نام ڈیٹاسیٹ کا، اور Axes
updates on each submission to reflect the input. For the convenience of the user, we’ll let them know if the input couldn’t be matched with a column name:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import TextBox fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2) df = pd.read_csv('winequality-red.csv') class EventHandler: def submit(feature_name): if feature_name != "" or feature_name != None: if feature_name in df: ax.cla() ax.plot(df[feature_name]) else: if len(textbox_ax.texts) > 2: del textbox_ax.texts[-1] textbox_ax.text(-2, 0.4, feature_name + ' was not found.') plt.draw() textbox_ax = plt.axes([0.7, 0.02, 0.2, 0.1])
textbox = TextBox(textbox_ax, 'Feature Name')
textbox.on_submit(EventHandler.submit) plt.show()
ہمارے پاس یہ دیکھنے کے لیے ایک سادہ چیک ہے کہ آیا فراہم کیا گیا ہے۔ feature_name
خالی ہے یا None
, in which case, we don’t do anything. If not, we check if the feature_name
میں موجود ہے DataFrame
, attaching a message that the feature wasn’t found if it’s not present. Before attaching the text though, we have to make sure that the previous message is removed, so that the new one doesn’t overlap with it. The axes.texts
پراپرٹی تمام کی فہرست ہے۔ Text
ایک پر مثالیں Axes
. جب سے Axes
پہلے سے ہی ایک ہے Text
مثال کے طور پر، ہمارا تعلق TextBox
, we don’t want to remove anything if there are 2 or less Text
instances present – the error message and the TextBox
لیبل
If above two, we’ve already got an error message, which should be removed.
اگر خصوصیت is موجودہ میں DataFrame
تاہم، ہم صاف کرتے ہیں۔ Axes
اور اس کا منصوبہ بنائیں:
اسپین سلیکٹرز کو شامل کرنا
اسپین سلیکٹرز can be used to allow the user to select a span of data and focus on it, setting the axis limits based on that selection. By default, many libraries support this functionality, though unfortunately, Matplotlib doesn’t and we’ll have to do this manually. Additionally, we’ll have to add an extra "ری سیٹ" بٹن اگر ہم چاہتے ہیں۔ دور کرنا ساتھ ہی.
شامل کرنا a اسپین سلیکٹر, we don’t need to dedicate an entire new Axes
for it – we can attach it to an existing one, which makes a lot of sense. When generating a SpanSelector
، ہم فراہم کرتے ہیں۔ Axes
اس کا تعلق ایونٹ ہینڈلر سے ہے، اس کے بعد 'horizontal'
or 'vertical'
، جو گھومتا ہے۔ Axes
اور اسپین سلیکٹر دونوں.
۔ useblit
دلیل کو عام طور پر سیٹ کیا جاتا ہے۔ True
because it enhances performance on most backends. Additionally, we’ve added a few styling properties, such as setting the alpha
اسپین سلیکٹر کے طور پر بنائے گئے مستطیل کا 0.5
اور facecolor
ایک اچھا tab:blue
:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
from matplotlib.widgets import Button fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2) df = pd.read_csv('AmesHousing.csv') ax.scatter(x = df['Year Built'], y = df['Total Bsmt SF'], alpha = 0.6) class EventHandler: def select_horizontal(x, y): ax.set_xlim(x, y) plt.draw() def reset(self): ax.set_xlim(df['Year Built'].min(), df['Year Built'].max()) plt.draw span_horizontal = SpanSelector(ax, EventHandler.select_horizontal, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='tab:blue')) button_ax = plt.axes([0.7, 0.02, 0.2, 0.07])
button = Button(button_ax, 'Reset')
button.on_clicked(EventHandler.reset) plt.show()
اسے چلانے سے ایک پلاٹ تیار ہوتا ہے جس پر ہم اسپین کو منتخب کر سکتے ہیں اور فراہم کردہ اقدار پر محور کی حدیں مقرر کر کے ان پر زوم ان کر سکتے ہیں:
سلائیڈرز کو شامل کرنا
Sliders مارکر کو سلائیڈ کرکے اور ایک قدر منتخب کرکے صارفین کو بہت سی قدروں کے درمیان انتخاب کرنے کی اجازت دیں۔ عام طور پر، سلائیڈرز کا استعمال پلاٹ پر کچھ قدر کو مسلسل اپ ڈیٹ کرنے کے لیے کیا جاتا ہے، جیسے کہ اس کی حد or یہاں تک کہ ایک خصوصیت. مثال کے طور پر، آپ ایک سلائیڈر کے ذریعے ایک مستقل کی قدر کو ایڈجسٹ کر سکتے ہیں، جس کے نتیجے میں ایک فنکشن متاثر ہوتا ہے جو اس مستقل پر انحصار کرتا ہے۔
Let’s write a script that allows us to change the Y and X-axis limits, through a slider, which will let us change the perspective from which we’re viewing our data:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2, left=0.2) df = pd.read_csv('winequality-red.csv')
plot, = ax.plot(df['volatile acidity']) class EventHandler: def update(val): ax.set_ylim(0, yslider.val) ax.set_xlim(0, xslider.val) plt.draw() xslider_ax = plt.axes([0.35, 0.03, 0.5, 0.07])
xslider = Slider( ax=xslider_ax, label="X-limit", valmin=0, valmax=len(df['volatile acidity']), valinit=len(df['volatile acidity']), orientation="horizontal"
) yslider_ax = plt.axes([0.03, 0.2, 0.07, 0.5])
yslider = Slider( ax=yslider_ax, label="Y-limit", valmin=0, valmax=3, valinit=1.5, orientation="vertical"
) xslider.on_changed(EventHandler.update)
yslider.on_changed(EventHandler.update) plt.show()
We’ve adjusted the padding to allow for a slider on the left and bottom of the Axes
، اور ایک سادہ لائن پلاٹ تیار کیا۔ ایک سلائیڈر شامل کرنے کے لیے ہمیں ایک بنانے کی ضرورت ہوتی ہے۔ Axes
اس کے لیے، دوسرے ویجٹ کی طرح، اور اسے تفویض کریں۔ ax
کی دلیل Slider
through the constructor. Additionally, we can set the minimum, maximum and initial values of the slider. These will typically be dynamic ranges, based on the data you’re plotting, but can also be manually set scalar values.
آخر میں، Slider
s can be oriented horizontally or vertically. Since they’re meant to be continually updated via a mouse-swipe – the on_changed()
function is used to trigger a response when a user gives input. We’ve tweaked the EventHandler
ایک کے ساتھ کلاس update()
وہ فنکشن جو بس کی بنیاد پر X اور Y-حدود کی قدروں کو ایڈجسٹ کرتا ہے۔ val
متعلقہ سلائیڈرز کا ue۔
اس کوڈ کو چلانے سے دو سلائیڈرز کے ساتھ ایک پلاٹ تیار ہو جائے گا، جسے ہم اس کے دائرہ کار کو تبدیل کرنے کے لیے استعمال کر سکتے ہیں۔ Axes
:
- تک رسائی حاصل
- تمام
- اجازت دے رہا ہے
- پہلے ہی
- ایک اور
- اے پی آئی
- نقطہ نظر
- دلائل
- ارد گرد
- شروع
- کیا جا رہا ہے
- باکس
- تعمیر میں
- فون
- پرواہ
- مقدمات
- تبدیل
- جانچ پڑتال
- کوڈ
- کالم
- سکتا ہے
- جوڑے
- تخلیق
- موجودہ
- موجودہ حالت
- اعداد و شمار
- سرشار کرنا
- پتہ چلا
- درجن سے
- متحرک
- آسانی سے
- ایج
- واقعہ
- واقعات
- مثال کے طور پر
- بہترین
- نمایاں کریں
- خصوصیات
- پہلا
- توجہ مرکوز
- ملا
- تقریب
- فعالیت
- جنرل
- جا
- عظیم
- سبز
- ہونے
- مدد
- یہاں
- کس طرح
- HTTPS
- خیال
- سمیت
- انڈکس
- انضمام
- IT
- لیبل
- بڑے
- لمیٹڈ
- لائن
- لسٹ
- میٹرکس
- سب سے زیادہ
- تعداد
- آپشنز کے بھی
- دیگر
- دوسری صورت میں
- کارکردگی
- نقطہ نظر
- حال (-)
- پریس
- عمل
- پیدا
- جائیداد
- ریڈیو
- رینج
- RE
- جواب
- نتائج کی نمائش
- واپسی
- سیفٹی
- کہا
- پیمانے
- سکرین
- منتخب
- احساس
- مقرر
- قائم کرنے
- سادہ
- چھوٹے
- So
- خلا
- شروع کریں
- حالت
- بیان
- امریکہ
- درجہ
- فراہمی
- حمایت
- سسٹمز
- ٹیسٹ
- کے ذریعے
- وقت
- سب سے اوپر
- اپ ڈیٹ کریں
- تازہ ترین معلومات
- us
- صارفین
- قیمت
- لنک
- کی نمائش
- نظر
- چاہے
- بغیر
- کام کیا
- کام کر
- تحریری طور پر
- X
- سال
- زوم