import tkinter as tk
from tkinter import messagebox label_num1 = [Link](root, text="First Number:")
def add_numbers(): label_num1.grid(row=0, column=0, padx=10, pady=10,
sticky="w")
try: entry_num1 = [Link](root, width=15)
num1_str = entry_num1.get() entry_num1.grid(row=0, column=1, padx=10, pady=10)
num2_str = entry_num2.get() label_num2 = [Link](root, text="Second Number:")
label_num2.grid(row=1, column=0, padx=10, pady=10,
number1 = float(num1_str) sticky="w")
number2 = float(num2_str) entry_num2 = [Link](root, width=15)
result = number1 + number2 entry_num2.grid(row=1, column=1, padx=10, pady=10)
result_label.config(text=f"Sum: {result}") calculate_button = [Link](root, text="Add Numbers",
command=add_numbers, bg="lightblue")
except ValueError: calculate_button.grid(row=2, column=0, columnspan=2,
pady=10)
[Link]("Invalid Input", "Please
enter valid numbers in both fields.") result_label = [Link](root, text="Sum: ", font=('Arial',
12, 'bold'))
result_label.config(text="Sum: Error") result_label.grid(row=3, column=0, columnspan=2,
root = [Link]() pady=10)
[Link]("Simple Adder App")
[Link]()
[Link]("300x200")
Matplotlib
10282025
Matplotlib?
• a low level graph plotting library in python that serves as a
visualization utility.
• was created by John D. Hunter.
• is an open source and we can use it freely.
• is mostly written in python, a few segments are written in C,
Objective-C and Javascript for Platform compatibility.
Installation Matplotlib?
1. Open Project Interpreter Settings:
•Go to File Settings
•Navigate to Project: [Your Project Name] Python Interpreter.
2. Add Matplotlib:
•Click the + (plus) icon on the right side of the packages list.
•In the available packages window, type matplotlib in the search bar.
•Select matplotlib and click Install Package.4
•You might also want to install numpy as it's the standard library for
generating data used with Matplotlib.
3. Apply Changes:
•Close the available packages window and click OK in the Settings
window.
•PyCharm will now configure your environment.
Draw a line in a diagram from position (0,0) to position (6,250):
import [Link] as plt
import numpy as np
xpoints = [Link]([0, 6])
ypoints = [Link]([0, 250])
[Link](xpoints, ypoints)
[Link]()
Plotting x and y points
The plot() function is used to draw points (markers) in a diagram.
By default, the plot() function draws a line from point to point.
The function takes parameters for specifying points in the diagram.
Parameter 1 is an array containing the points on the x-axis.
Parameter 2 is an array containing the points on the y-axis.
Try this!
Draw a line in a diagram from position (1, 3) to position (8, 10):
Matplotlib markers
marker to emphasize each point with specified marker:
import [Link] as plt
import numpy as np
ypoints = [Link]([3, 8, 1, 10])
[Link](ypoints, marker = 'o')
[Link]()
Marker Reference
Format Strings fmt
is written with syntax:marker|line|color
import [Link] as plt
import numpy as np
ypoints = [Link]([3, 8, 1, 10])
[Link](ypoints, 'o:r')
[Link]()
Line Reference
Create Labels for a Plot
use the xlabel() and ylabel() functions to set a label for the x- and y-axis.
import numpy as np
import [Link] as plt
x=
[Link]([80, 85, 90, 95, 100, 105, 110, 115, 120
, 125])
y=
[Link]([240, 250, 260, 270, 280, 290, 300, 310
, 320, 330])
font1 = {'family':'serif','color':'blue','size':20}
font2 = {'family':'serif','color':'darkred','size':15}
[Link]("Sports Watch Data", fontdict = font1)
[Link]("Average Pulse", fontdict = font2)
[Link]("Calorie Burnage", fontdict = font2)
[Link](x, y)
[Link]()
Matplotlib Grid
import numpy as np
import [Link] as plt
x=
[Link]([80, 85, 90, 95, 100, 105, 110, 115, 12
0, 125])
y=
[Link]([240, 250, 260, 270, 280, 290, 300, 31
0, 320, 330])
[Link]("Sports Watch Data")
[Link]("Average Pulse")
[Link]("Calorie Burnage")
[Link](x, y)
[Link](color = 'green', linestyle = '--', linewidth
= 0.5)
[Link]()
Display Multiple Plots
With the subplot() function you can draw multiple plots in one figure:
import [Link] as plt
import numpy as np
#plot 1:
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](1, 2, 1)
[Link](x,y)
#plot 2:
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](1, 2, 2)
[Link](x,y)
[Link]()
The subplot() Function
The subplot() function takes three arguments that describes the layout of the figure.
The layout is organized in rows and columns, which are represented by
the first and second argument.
The third argument represents the index of the current plot.
[Link](1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
[Link](1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.
Display Multiple Plots
Draw 2 plots on top of each other:
import [Link] as plt
import numpy as np
#plot 1:
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](2, 1, 1)
[Link](x,y)
#plot 2:
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](2, 1, 2)
[Link](x,y)
[Link]()
Sample1
import [Link] as plt # 3. Add labels and title (good practice)
import numpy as np [Link]('My First Matplotlib Plot in
PyCharm')
[Link]('X-axis values')
# 1. Prepare Data (using numpy for a
simple example) [Link]('Y-axis values')
x = [Link](0, 10, 100) [Link]()
y = [Link](x) [Link](True) # Optional: add a grid
# 2. Create the plot # 4. Display the plot
[Link](figsize=(8, 4)) [Link]().
# Optional: set the figure size
[Link](x, y, label='Sine Wave',
color='blue')
Sample2
import [Link] as plt # --- 3. Customization ---
import numpy as np [Link]('Sine and Cosine Waves Over One
# --- 1. Prepare Data --- Cycle')
# Generate 100 points between 0 and 2*pi [Link]('Angle (Radians)')
x = [Link](0, 2 * [Link], 100) [Link]('Amplitude')
y_sin = [Link](x) [Link](loc='upper right')
y_cos = [Link](x) # Show legend for labels
# --- 2. Create Plot --- [Link](True, linestyle=':', alpha=0.6)
[Link](figsize=(10, 5)) # Add a faint grid
# Create a figure of size 10x5 inches [Link](0, color='black', linewidth=0.5)
# Plot the two functions # Add a horizontal line at y=0
[Link](x, y_sin, label='Sine ($\sin(x)$)', # --- 4. Display Plot ---
color='blue', linestyle='-') [Link]()
[Link](x, y_cos, label='Cosine ($\cos(x)$)',
color='red', linestyle='--')
Sample3
import [Link] as plt # --- 4. Customization ---
import numpy as np ax.set_title('Scatter Plot: Correlation Between Two
Variables')
# --- 1. Prepare Data --- ax.set_xlabel('Variable A (Random Normal)')
# Create synthetic data for two variables ax.set_ylabel('Variable B (Dependent)')
[Link](True, alpha=0.3)
[Link](42) # for reproducibility
data_a = [Link](loc=10, scale=3, size=50) # [Link](
Mean 10, SD 3 'Possible correlation visible',
data_b = 5 + 0.8 * data_a + [Link](loc=0, xy=(15, 18),
scale=2, size=50) # Correlated with some noise
xytext=(18, 16),
arrowprops=dict(facecolor='red', shrink=0.05,
# --- 2. Create Figure and Axes (OO Approach) --- width=1)
fig, ax = [Link](figsize=(8, 6)) )
# --- 3. Create Scatter Plot --- # --- 5. Display Plot ---
[Link](data_a, data_b, s=50, c='green', alpha=0.7, [Link]()
edgecolors='black', linewidths=0.5)
Sample4
import [Link] as plt # --- 3. Customization ---
[Link]('Monthly Sales by Fruit Category')
# --- 1. Prepare Data --- [Link]('Fruit Category')
categories = ['Apples', 'Oranges', 'Bananas', [Link]('Sales Volume (Units)')
'Grapes', 'Pears'] [Link](0, 700) # Set Y-axis limit for better
sales = [450, 320, 580, 290, 410] # Example visualization
monthly sales figures
# Add data labels on top of the bars
# --- 2. Create Plot --- for bar in bars:
[Link](figsize=(8, 5)) yval = bar.get_height()
[Link](bar.get_x() + bar.get_width()/2.0,
# Create the bar chart yval + 10, int(yval), ha='center', va='bottom')
bars = [Link](categories, sales,
color=['#4CAF50', '#FF9800', '#FDD835', # --- 4. Display Plot ---
'#7E57C2', '#607D8B'])
[Link]()
Sample5
import [Link] as plt
import numpy as np
y = [Link]([35, 25, 25, 15])
mylabels =
["Apples", "Bananas", "Cherries", "Dates"]
[Link](y, labels = mylabels)
[Link](title = "Four Fruits:")
[Link]()
Thank you for
learning DSA Python
with me!