Data Visualisation With Python
Data Visualisation With Python
What is Python?
1a) Write a python program to find the best of two test average marks out of three test’s
marks accepted from the user.
Avg = total / 2
print ("The average of the best two test marks is: ",Avg)
OUTPUT
Enter the marks in the first test: 45
Enter the marks in second test: 78
Enter the marks in third test: 23
The average of the best two test marks is: 61.5
1b. Develop a Python program to check whether a given number is palindrome or not and
also count the number of occurrences of each digit in the input number.
OUTPUT 1
Dept of ISE 2023-24Page 2
Data visualisation with Python - BCS358D
OUTPUT 2
Enter a value : 12223
Not Palindrome
2 appears 1 times
2 appears 3 times
3 appears 1 times
4
Decision Constructs
Decision making is the most important aspect of almost all the programming languages. As
the name implies, decision making allows us to run a particular block of code for a
particular decision. Here, the decisions are made on the validity of the particular
conditions. Condition checking is the backbone of decision making.
Statement Description
While loop
The Python while loop allows a part of the code to be executed until the given
condition returns false. It is also known as a pre-tested loop.
While
expression:
statements
Example:
PROGRAM :
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")
OUTPUT:
Enter a number : 0
Error in input
Enter a number : 7
fn(7) = 8
Python Function
Functions are the most important aspect of an application. A function can be defined as
the organized block of reusable code, which can be called whenever required.Python
allows us to divide a large program into the basic building blocks known as a function.
The function contains the set of programming statements enclosed by {}. A function can
be called multiple times to provide reusability and modularity to the Python program.
The Function helps to programmer to break the program into the smaller part. It
organizes the code very effectively and avoids the repetition of the code. As the program
grows, function makes the program more organized.
Python provide us various inbuilt functions like range() or print(). Although, the
user can create its functions, which can be called user-defined functions.
There are mainly two types of functions.
User-define functions - The user-defined functions are those define by the user to perform
the specific task. Built-in functions - The built-in functions are those functions that are
pre-defined in Python.
The def keyword, along with the function name is used to define the function. The identifier
rule must follow the function name.
A function accepts the parameter (argument), and they can be optional.
The function block is started with the colon (:), and block statements must be at the same
indentation. The return statement is used to return the value. A function can have only one
return Function Calling
In Python, after the function is created, we can call it from another function. A function must be defined
before the function call; otherwise, the Python interpreter gives an error.To call the function, use the
function name followed by the parentheses
Consider the following example of a simple example that prints the message "Hello World".
function
definition def
hello_world():
print("helloworld")
# function calling
hello_world()
Output:
hello world
The return statement
The return statement is used at the end of the function and returns the result of the
function. It terminates the function execution and transfers the result where the function is
called. The return statement cannot be used outside of the function.
Syntax
return [expression_list]
Arguments in function
The arguments are types of information which can be passed into the function. The
arguments are specified in the parentheses. We can pass any number of arguments, but
they must be separate them with a comma. #Python function to calculate the sum of two
variables
#defining the function
def sum (a,b):
return a+b;
Program:
def binary_to_decimal(binary_str):
decimal_num = 0
binary_str = binary_str[::-1] # Reverse the binary string
for i in range(len(binary_str)):
if binary_str[i] == '1':
decimal_num += 2**i
return decimal_num
def octal_to_hexadecimal(octal_str):
decimal_num = int(octal_str, 8) # Convert octal string to decimal
hexadecimal_str = hex(decimal_num).upper()[2:] # Convert decimal to hexadecimal
return hexadecimal_str
# Main program
while True:
print("Choose an option:")
print("1. Convert Binary to Decimal")
print("2. Convert Octal to Hexadecimal")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
binary_str = input("Enter a binary number: ")
decimal_num = binary_to_decimal(binary_str)
print(f"Decimal equivalent: {decimal_num}")
elif choice == '2':
octal_str = input("Enter an octal number: ")
hexadecimal_str = octal_to_hexadecimal(octal_str)
print(f"Hexadecimal equivalent: 0x{hexadecimal_str}")
elif choice == '3':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.")
OUTPUT:
Choose an option:
1. Convert Binary to Decimal
2. Convert Octal to Hexadecimal
3. Exit
Enter your choice (1/2/3): 1
Enter a binary number: 1011
Decimal equivalent: 11
Choose an option:
1. Convert Binary to Decimal
2. Convert Octal to Hexadecimal
3. Exit
Enter your choice (1/2/3): 2
Enter an octal number: 345
Hexadecimal equivalent: 0xE5
Choose an option:
1. Convert Binary to Decimal
2. Convert Octal to Hexadecimal
3. Exit
Enter your choice (1/2/3): 3
Exiting the program. Goodbye!
3a. Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters.
A String in Python consists of a series or sequence of characters - letters, numbers, and
special characters. Strings are marked by quotes:
● single quotes (' ') Eg, 'This a
for ch in sentence:
if '0' <= ch <= '9':
digCnt += 1
elif 'A' <= ch <= 'Z':
upCnt += 1
elif 'a' <= ch <= 'z':
loCnt += 1
print("This sentence has", digCnt, "digits", upCnt, "upper case letters", loCnt,
"lower case letters")
OUTPUT:
3 b) Write a Python program to find the string similarity between two given strings .
OUTPUT:
Enter String 1
dsatmcse
Enter String 2
dsatmcse
Similarity between two said strings:
1.0
Enter String 1
cse department at dsatm
Enter String 2
ise department at dsatm
Similarity between two said strings:
0.9565217391304348
4a. Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
A bar plot or 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. The matplotlib API in Python provides the bar() function which
can be used in MATLAB style use or as an object-oriented API.
The syntax of the bar() function to be used with the axes is as follows:-
plt.bar(x, height, width, bottom, align)
The function creates a bar plot bounded with a rectangle depending on the given parameters.
Program:
# layout configuration
pyplot.ylabel('Usage in %')
pyplot.xlabel('Programming Languages')
OUTPUT:
4b. Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
matplotlib.pyplot.scatter()
Scatter plots are used to observe relationship between variables and uses dots to represent the
relationship between them. The scatter() method in the matplotlib library is used to draw a scatter
plot. Scatter plots are widely used to represent relation among variables and how change in one
affects the other.
Program:
import matplotlib.pyplot as plt
plt.scatter(price, sales_per_day)
plt.show()
OUTPUT:
The hist() function will use an array of numbers to create a histogram, the array is sent into the
function as an argument.
PROGRAM:
np.random.seed(42)
x = np.random.normal(size=1000)
OUTPUT:
# Creating dataset
cars = ['AUDI', 'BMW', 'FORD','TESLA', 'JAGUAR', 'MERCEDES']
data = [23, 17, 35, 29, 12, 41]
# Creating plot
fig = plt.figure(figsize =(10, 7))
plt.pie(data, labels = cars)
# show plot
plt.show()
# Draw a Pie Chart using Matplotlib
OUTPUT:
OUTPUT:
6 b) Write a Python program to illustrate liner plotting with line formatting using
Matplotlib.
OUTPUT:
7. Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
OUTPUT:
8 a) Write a Python program to explain working with bokeh line graph using Annotations
and Legends.
Bokeh is a Python interactive data visualization. It renders its plots using HTML and
javascript. It targets modern web browsers for presentation providing elegant, concise
construction of novel graphics with high-performance interactivity.
Bokeh can be used to plot a line graph. Plotting a line graph can be done using
the line() method of the plotting module.
● x : x-coordinates of the points to be plotted
● y : y-coordinates of the points to be plotted
● line_alpha : percentage value of line alpha, default is 1
● line_cap : value of line cap for the line, default is butt
● line_color : color of the line, default is black
● line_dash : value of line dash such as :
● solid
● dashed
● dotted
● dotdash
● dashdot
default is solid
● line_dash_offset : value of line dash offset, default is 0
● line_join : value of line join, default in bevel
● line_width : value of the width of the line, default is 1
● name : user-supplied name for the model
● tags : user-supplied values for this model
Other Parameters :
● alpha : sets all alpha keyword arguments at once
● color : sets all color keyword arguments at once
● legend_field : name of a column in the data source that should be used
● legend_group : name of a column in the data source that should be used
● legend_label : labels the legend entry
● muted : determines whether the glyph should be rendered as muted or not,
default is False
● name : optional user-supplied name to attach to the renderer
● source : user-supplied data source
● view : view for filtering the data source
● visible : determines whether the glyph should be rendered or not, default is True
● x_range_name : name of an extra range to use for mapping x-coordinates
● y_range_name : name of an extra range to use for mapping y-coordinates
● level : specifies the render level order for this glyph
Returns : an object of class GlyphRenderer
# Sample data
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 6, 8, 10]
y2 = [1, 3, 5, 7, 9]
# Add annotations
label1 = Label(x=3, y=8, text="Annotation 1", text_font_size="12pt", text_color="blue")
label2 = Label(x=2.5, y=3, text="Annotation 2", text_font_size="12pt", text_color="red")
p.add_layout(label1)
p.add_layout(label2)
# Create a legend
legend = Legend(items=[("Line 1", [line1]), ("Line 2", [line2])], location="top_left")
p.add_layout(legend)
OUTPUT:
8. b) Write a Python program for plotting different types of plots using Bokeh.
Python Bokeh is a Data Visualization library that provides interactive charts and plots. Bokeh
renders its plots using HTML and JavaScript that uses modern web browsers for presenting
elegant, concise construction of novel graphics with high-level interactivity.
bokeh.plotting: This is the mid-level interface that provides Matplotlib or MATLAB like
features for plotting. It deals with the data that is to be plotted and creating the valid axes, grids,
and tools. The main class of this interface is the Figure class.
# Line plot
p1 = figure(title="Line Plot", width=400, height=300)
p1.line(x, y, line_width=2, color="blue")
# Scatter plot
source = ColumnDataSource(data=dict(x=x, y=y))
p2 = figure(title="Scatter Plot", width=400, height=300)
p2.circle('x', 'y', source=source, size=6, color="red")
# Bar plot
categories = ['A', 'B', 'C', 'D']
values = [4, 7, 1, 2]
p3 = figure(x_range=categories, title="Bar Plot", width=400, height=300)
p3.vbar(x=categories, top=values, width=0.5, color="green")
# Histogram
data = np.random.normal(0, 1, 1000)
p4 = figure(title="Histogram", width=400, height=300)
hist, edges = np.histogram(data, bins=20)
p4.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color="purple",
line_color="black")
OUTPUT:
fig.show()
OUT PUT:
10. a) Write a Python program to draw Time Series using Plotly Libraries
Time series can be represented using either plotly.express functions (px.line, px.scatter, px.bar etc)
or plotly.graph_objects charts objects (go.Scatter, go.Bar etc). For more examples of such charts,
see the documentation of line and scatter plots or bar charts. Plotly auto-sets the axis type to a date
format when the corresponding data are either ISO-formatted date strings or if they're a date
pandas column or datetime NumPy array.
import plotly.graph_objects as go
import pandas as pd
# Sample time series data (you can replace this with your own data)
data = {
'Date': pd.date_range(start='2023-01-01', periods=10, freq='D'),
'Value': [10, 12, 15, 20, 18, 22, 25, 28, 30, 32]
}
# Create a DataFrame
df = pd.DataFrame(data)
OUTPUT :
Plotly is a Python library that is very popular among data scientists to create interactive data
visualizations. One of the visualizations available in Plotly is Choropleth Maps. Choropleth maps
are used to plot maps with shaded or patterned areas which are proportional to a statistical variable.
They are composed of colored polygons. They are used for representing spatial variations of a
quantity.
To create them, we require two main types of inputs –
● Geometric information –
● this can be a GeoJSON file (here each feature has an id or some identifying
value in properties, or
● this can be built-in geometries of plotly – US states and world countries
● A list of values with feature identifier as index
# Sample data for Indian states (replace with your own data)
data = {
'State': ['Delhi', 'Maharashtra', 'Tamil Nadu', 'Karnataka', 'Kerala'],
'Latitude': [28.6139, 19.7515, 11.1271, 15.3173, 10.8505],
'Longitude': [77.2090, 75.7139, 78.6569, 75.7139, 76.2711],
Dept of ISE 2023-24Page 25
Data visualisation with Python - BCS358D
'Value': [100, 200, 300, 400, 500] # Sample value associated with each state
}
OUTPUT:
QUESTIONS
1 What is data visualization, and why is it important in data analysis and interpretation?
2 Can you explain the key libraries in Python commonly used for data visualization?
3 How do you import and load data for visualization in Python, and which libraries or methods
do you use for this purpose?
4 What are the differences between Matplotlib and Seaborn, and when would you choose one
over the other for data visualization?
5 Explain the basic structure of a Matplotlib or Seaborn plot. What are the essential components?
6 How do you create different types of plots, such as line plots, scatter plots, bar charts, and
histograms, in Matplotlib or Seaborn?
7 Discuss the concept of customizing and styling visualizations in Python.
8 What kind of customizations can you apply to plots?
9 What is the importance of choosing the right color palette for data visualizations?
10 How do you select an appropriate one in Seaborn?
11 How can you handle missing data or outliers when preparing data for visualization?
12 What is the role of data preprocessing in data visualization, and can you provide examples of
common preprocessing tasks?
13 How can you create interactive visualizations in Python, and which libraries would you use for
this purpose?
14 What is the role of data aggregation and summarization in creating meaningful visualizations?