0% found this document useful (0 votes)
0 views

Python Unit 5

The document provides an overview of data visualization using Matplotlib in Python, detailing various chart types such as line charts, bar charts, histograms, scatter plots, and pie charts, along with practical implementation examples. It also covers creating graphical user interfaces (GUIs) using Tkinter, including widgets like labels, checkbuttons, and radiobuttons, with code examples. Additionally, it explains how to connect to a MySQL database using MySQL-Connector in Python, including connection syntax and executing select queries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Python Unit 5

The document provides an overview of data visualization using Matplotlib in Python, detailing various chart types such as line charts, bar charts, histograms, scatter plots, and pie charts, along with practical implementation examples. It also covers creating graphical user interfaces (GUIs) using Tkinter, including widgets like labels, checkbuttons, and radiobuttons, with code examples. Additionally, it explains how to connect to a MySQL database using MySQL-Connector in Python, including connection syntax and executing select queries.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

UNIT-5

Q) Data Visualization using Matplotlib in Python or Explain different type of charts in Python
Matplotlib is a powerful and widely-used Python library for creating static, animated and interactive data
visualizations. In this article, we will provide a guide on Matplotlib and how to use it for data visualization with
practical implementation. Matplotlib supports a variety of plots including line charts, bar charts, histograms,
scatter plots, etc. Let’s understand them with implementation using pyplot.
1. Line Chart
Line chart is one of the basic plots and can be created using the plot() function. It is used to represent a
relationship between two data X and Y on a different axis.
Example:
import matplotlib.pyplot as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
plt.plot(x, y)
plt.title("Line Chart")
plt.ylabel('Y-Axis')
plt.xlabel('X-Axis')
plt.show()

2. Bar Chart
A bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is
proportional to the values which they represent. The bar plots can be plotted horizontally or vertically. A bar
chart describes the comparisons between the different categories. It can be created using the bar() method.
In the below example we will use the tips dataset. Tips database is the record of the tip given by the customers
in a restaurant for two and a half months in the early 1990s. It contains 6 columns as total_bill, tip, sex, smoker,
day, time, size.
Example:
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('tips.csv')
x = data['day']
y = data['total_bill']
plt.bar(x, y)
plt.title("Tips Dataset")
plt.ylabel('Total Bill')
plt.xlabel('Day')
plt.show()
3. Histogram:-A histogram is basically used to represent data provided in a form of some groups. It is a type of
bar plot where the X-axis represents the bin ranges while the Y-axis gives information about frequency.
The hist() function is used to compute and create histogram of x.
Example:
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('tips.csv')
x = data['total_bill']
plt.hist(x)
plt.title("Tips Dataset")
plt.ylabel('Frequency')
plt.xlabel('Total Bill')
plt.show()

4. Scatter Plot:-Scatter plots are used to observe relationships between variables. The scatter() method in the
matplotlib library is used to draw a scatter plot.
Example:
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('tips.csv')
x = data['day']
y = data['total_bill']
plt.scatter(x, y)
plt.title("Tips Dataset")
plt.ylabel('Total Bill')
plt.xlabel('Day')
plt.show()

5. Pie Chart:-Pie chart is a circular chart used to display only one series of data. The area of slices of the pie
represents the percentage of the parts of the data. The slices of pie are called wedges. It can be created using
the pie() method.
Syntax:
matplotlib.pyplot.pie(data, explode=None, labels=None, colors=None, autopct=None, shadow=False)
Example:
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('tips.csv')
cars = ['AUDI', 'BMW', 'FORD', 'TESLA', 'JAGUAR',]
data = [23, 10, 35, 15, 12]
plt.pie(data, labels=cars)
plt.title("Car data")
plt.show()

2) Using Python. Graphical User Interfaces


To create graphical user interfaces (GUIs) in Python, you can use libraries like Tkinter, wxPython, PyQt, or
PySide, which allow you to build interactive applications with windows, buttons, and other widgets.
Here's a breakdown:
1. Tkinter:
What it is: Tkinter is Python's standard GUI toolkit, included with standard Python installations.
How to use it:
Import the tkinter module: import tkinter as tk.
Create a main window: window = tk.Tk().
Add widgets (buttons, labels, text boxes, etc.): button = tk.Button(window, text="Click Me").
Use geometry managers (like pack(), grid(), or place()) to arrange widgets: button.pack().
Start the event loop: window.mainloop().
Example:
Python
import tkinter as tk
window = tk.Tk()
window.title("My First GUI")
label = tk.Label(window, text="Hello, Tkinter!")
label.pack()
window.mainloop()
Python Tkinter – Label
Tkinter Label is a widget that is used to implement display boxes where you can place text or images. The text
displayed by this widget can be changed by the developer at any time you want. It is also used to perform tasks
such as underlining the part of the text and spanning the text across multiple lines.
Syntax: Label ( master, option )
Parameters:
Tkinter Label Options
anchor: The default is anchor=CENTER, which centers the text in the available space.
bg: This option is used to set the normal background color displayed behind the label and indicator.
height:This option is used to set the vertical dimension of the new frame.
width:Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its
contents.
bd:This option is used to set the size of the border around the indicator. Default bd value is set on 2 pixels.
font: the font option is used to specify in what font that text in the label will be displayed.
cursor:It is used to specify what cursor to show when the mouse is moved over the label. The default is to use
the standard cursor.
textvariable If the variable is changed, the label text is updated.
bitmap:It is used to set the bitmap to the graphical object specified
fg:The label clior, used for text and bitmap labels.
image: This option is used to display a static image in the label widget.
padx:This option is used to add extra spaces between left and right of the text within the label.The default value
for this option is 1.
pady:This option is used to add extra spaces between top and bottom of the text within the label.The default
value for this option is 1.
justify:This option is used to define how to align multiple lines of text. Use LEFT, RIGHT, or CENTER as its
values.
relief: This option is used to specify appearance of a decorative border around the label. The default value for
this option is FLAT.
Example
import tkinter as tk
# Create the main window
root = tk.Tk()
root.geometry("400x250") # Set window size
root.title("Welcome to My App") # Set window title
# Create a StringVar to associate with the label
text_var = tk.StringVar()
text_var.set("Hello, World!")
# Create the label widget with all options
label = tk.Label(root,
textvariable=text_var,
anchor=tk.CENTER,
bg="lightblue",
height=3,
width=30,
bd=3,
font=("Arial", 16, "bold"),
cursor="hand2",
fg="red",
padx=15,
pady=15,
justify=tk.CENTER,
relief=tk.RAISED,
underline=0,
wraplength=250
)
# Pack the label into the window
label.pack(pady=20) # Add some padding to the top
# Run the main event loop
root.mainloop()
Creating a Checkbutton Widget
Checkbuttons (also called checkboxes) are simple widgets which can be checked and unchecked by the
user. When toggled Checkbutton widgets can call methods or functions using the command argument. The
current state of a Checkbutton is stored in an external control variable. Control variables are created using
Tkinter's variable classes, such as IntVar, DoubleVar, BooleanVar, and StringVar. The linked control variable
will be updated to reflect any changes in the widget.
import tkinter as tk
root = tk.Tk()
root.title("Checkbutton")
root.geometry("200x100")
def select_items():
label.config(text=f"Selected: {bool(variable.get())}")
variable = tk.IntVar()
item = tk.Checkbutton(
root,
text="Tuna fish",
command=select_items,
variable=variable,
)
item.pack(anchor="w", padx=10, pady=10)
label = tk.Label(root, text="Selected: False")
label.pack(
anchor="w",
padx=10,
pady=10,
)
root.mainloop()
RadioButton in Tkinter | Python
The Radiobutton is a standard Tkinter widget used to implement one-of-many selections. Radiobuttons can
contain text or images, and you can associate a Python function or method with each button. When the button
is pressed, Tkinter automatically calls that function or method.
Syntax:
button = Radiobutton(master, text=”Name on Button”, variable = “shared variable”, value = “values of each
button”, options = values, …)
shared variable = A Tkinter variable shared among all Radio buttons
value = each radiobutton should have different value otherwise more than 1 radiobutton will get selected.
from tkinter import *
master = Tk()
master.geometry("175x175")
v = StringVar(master, "1")
values = {"RadioButton 1" : "1",
"RadioButton 2" : "2",
"RadioButton 3" : "3",
"RadioButton 4" : "4",
"RadioButton 5" : "5"}

Creating a simple information dialog


import tkinter as tk
from tkinter import messagebox
def show_info_dialog():
messagebox.showinfo("Information", "This is a simple information dialog.")
root = tk.Tk()
root.title("Information Dialog Example")
info_button = tk.Button(root, text="Show Info Dialog", command=show_info_dialog)
info_button.pack(padx=20, pady=20)
root.mainloop()
Q) Connect MySQL database using MySQL-Connector Python
Connecting to the Database
The mysql.connector provides the connect() method used to create a connection between the MySQL database
and the Python application. The syntax is given below.
Syntax:
Conn_obj= mysql.connector.connect(host = <hostname>, user = <username>, passwd = <password>)
The connect() function accepts the following arguments.
Hostname – It represents the server name or IP address on which MySQL is running.
Username – It represents the name of the user that we use to work with the MySQL server. By default, the
username for the MySQL database is root.
Password – The password is provided at the time of installing the MySQL database. We don’t need to pass a
password if we are using the root.
Database – It specifies the database name which we want to connect. This argument is used when we have
multiple databases.
In the following example we will be connecting to MySQL database using connect()
Example:

Python3
# Python program to connect
# to mysql database
import mysql.connector
# Connecting from the server
conn = mysql.connector.connect(user = 'username',
host = 'localhost',
database = 'database_name')
print(conn)
# Disconnecting from the server
conn.close()
Select Query
After connecting with the database in MySQL we can select queries from the tables in it. Syntax:
In order to select particular attribute columns from a table, we write the attribute names.
SELECT attr1, attr2 FROM table_name
In order to select all the attribute columns from a table, we use the asterisk ‘*’ symbol.
SELECT * FROM table_name

You might also like