DATA VISUALIZATION WITH 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.
marks1 = int(input("Enter IA1 marks: "))
marks2 = int(input("Enter IA2 marks: "))
marks3 = int(input("Enter IA3 marks: "))
minimum = min(marks1,marks2,marks3)
sumof2 = marks1 + marks2 + marks3 - minimum
avgof2 = sumof2 / 2
print("Average of best 2 = ", avgof2)
OUTPUT:
Enter IA1 marks: 30
Enter IA2 marks: 40
Enter IA3 marks: 30
Average of best 2 = 35.0
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.
val = int(input("Enter a value : "))
str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i), "appears", str_val.count(str(i)), "times");
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
OUTPUT 1:
Enter a value : 234
Not Palindrome
2 appears 1 times
3 appears 1 times
4 appears 1 times
OUTPUT 2:
Enter a value : 121
Palindrome
1 appears 2 times
2 appears 1 times
2 a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a
value for N (where N >0) as input and pass this value to the function. Display suitable error
message if the condition for input value is not followed.
def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)
num = int(input("Enter a value for n: "))
if num > 0:
print("fn(", num, ") = ", fn(num), sep="")
else:
print("Error in input")
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
OUTPUT:
Enter a value for n: 5
fn(5) = 3
2 b) Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.
def BinToDec(b):
return int(b, 2)
print("Enter the Binary Number: ", end="")
bnum = input()
dnum = BinToDec(bnum)
print("\nEquivalent Decimal Value = ", dnum)
def OctToHex(o):
return hex(int(o, 8))
print("Enter Octal Number: ", end="")
onum = input()
hnum = OctToHex(onum)
print("\nEquivalent Hexadecimal Value =", hnum[2:].upper())
OUTPUT:
Enter the Binary Number: 10001
Equivalent Decimal Value = 17
Enter Octal Number: 235
Equivalent Hexadecimal Value = 9D
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
3 a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters and lowercase letters.
s = input("Enter a sentence: ")
w, d, u, l = 0, 0, 0, 0
l_w = [Link]()
w = len(l_w)
for c in s:
if [Link]():
d=d+1
elif [Link]():
u=u+1
elif [Link]():
l=l+1
print ("No of Words: ", w)
print ("No of Digits: ", d)
print ("No of Uppercase letters: ", u)
print ("No of Lowercase letters: ", l)
OUTPUT:
Enter a sentence: I am Sinchana M N
No of Words: 5
No of Digits: 0
No of Uppercase letters: 4
No of Lowercase letters: 9
3 b) Write a Python program to find the string similarity between two given strings
import difflib
text1 = "welcome to Python Lab"
text2 = "welcome to Program Lab"
text3 = "Computer engineering"
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
sequence = [Link](isjunk=None, a=text1, b=text2)
difference = [Link]()*100
difference = round(difference,1)
print(str(difference) + "% match")
OUTPUT:
80.0% match
4 a) Write a Python program to Demonstrate how to Draw a Bar Plot using Matplotlib.
import numpy as np
import [Link] as plt
# creating the dataset
data = {'C':20, 'C++':15, 'Java':30, 'Python':35}
courses = list([Link]())
values = list([Link]())
fig = [Link](figsize = (10, 5))
# creating the bar plot
[Link](courses, values, color ='maroon', width = 0.4)
[Link]("Courses offered")
[Link]("No. of students enrolled")
[Link]("Students enrolled in different courses")
[Link]()
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
OUTPUT:
4 b ) Write a Python program to Demonstrate how to Draw a Scatter Plot using Matplotlib.
import [Link] as plt
x =[5, 7, 8, 7, 2, 17, 2, 9,
4, 11, 12, 9, 6]
y =[99, 86, 87, 88, 100, 86,
103, 87, 94, 78, 77, 85, 86]
[Link](x, y, c ="blue")
# To show the plot
[Link]()
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
OUTPUT :
5 a) Write a Python program to Demonstrate how to Draw a Histogram Plot using
Matplotlib.
import [Link] as plt
import numpy as np
x = [Link](140, 10, 250)
[Link](x)
[Link]()
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
5 b) Write a Python program to Demonstrate how to Draw a Pie Chart using Matplotlib.
# Import libraries
from matplotlib import pyplot as plt
import numpy as np
# Creating dataset
cars = ['ISE', 'CSE', 'ME', 'EEE', 'EC', 'CIVIL']
data = [23, 17, 35, 29, 12, 41]
# Creating plot
fig = [Link](figsize =(10, 7))
[Link](data, labels = cars)
# show plot
[Link]()
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
OUTPUT :
6 a) Write a Python program to illustrate Linear Plotting using Matplotlib.
# importing the required libraries
import [Link] as plt
import numpy as np
# define data values
x = [Link]([1, 2, 3, 4]) # X-axis points
y = x*2 # Y-axis points
[Link](x, y) # Plot the chart
[Link]() # display
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
Output:
6 b) Write a Python program to illustrate liner plotting with line formatting using Matplotlib
from matplotlib import pyplot as plt
[Link]()
ages_x = [18, 19, 20, 21, 22, 23, 24, 25, 26, 30]
py_dev_y = [20046, 17100, 20000, 24744, 30500, 37732, 41247, 45372, 48876, 53850]
[Link](ages_x, py_dev_y, label='Python')
js_dev_y = [16446, 16791, 18942, 21780, 25704, 29000, 34372, 37810, 43515, 46823]
[Link](ages_x, js_dev_y, label='JavaScript')
dev_y = [17784, 16500, 18012, 20628, 25206, 30252, 34368, 38496, 42000, 46752]
[Link](ages_x, dev_y, color='#444444', linestyle='--', label='All Devs')
[Link]('Ages')
[Link]('Median Salary (USD)')
[Link]('Median Salary (USD) by Age')
[Link]()
plt.tight_layout()
[Link]('[Link]')
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
[Link]()
Output:
7) Write a Python program which explains uses of customizing seaborn plots with Aesthetic
functions.
from [Link] import load_iris
import pandas as pd
import numpy as np
import seaborn as sns
import [Link] as plt
iris = load_iris()
iris_df = [Link](data= np.c_[iris['data'], iris['target']],columns= iris['feature_names'] +
['target'])
[Link](figsize=(8, 6))
[Link](x="sepal length (cm)", y="sepal width (cm)", hue="target", data=iris_df,
palette="bright")
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
[Link]("Scatterplot of Iris Dataset")
[Link]()
[Link](style="darkgrid")
OUTPUT:
b)
[Link](x="target", y="sepal length (cm)", data=iris_df)
[Link]("Violin plot of Sepal Length")
[Link]()
Output:
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
8 (a) Write a Python program to explain working with bokeh line graph using Annotations and Legends.
from [Link] import figure, output_file, show
output_file("[Link]")
graph = figure(title = "Bokeh Line Graph")
x = [1, 2, 3, 4, 5]
y = [1, 6, 8, 2, 3]
[Link](x, y)
show(graph)
Output:
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
b) Write a Python program for plotting different types of plots using Bokeh.
from [Link] import show, output_notebook
from [Link] import figure
from [Link] import ColumnDataSource
# Scatter plot
output_notebook()
scatter = figure(title="Scatter Plot", x_axis_label='X data', y_axis_label='Y data')
[Link]([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=20, color="navy", alpha=0.5)
show(scatter)
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
# Line plot
line = figure(title="Line Plot", x_axis_label='X data', y_axis_label='Y data')
[Link]([1, 2, 3, 4, 5], [5, 6, 7, 8, 9], line_width=2)
show(line)
# Bar plot
bar = figure(title="Bar Plot", x_axis_label='X data', y_axis_label='Y data')
data = ColumnDataSource(data=dict(x=[1, 2, 3, 4, 5], y=[5, 6, 7, 8, 9]))
[Link](x='x', top='y', width=0.5, source=data, color="navy")
show(bar)
Output:
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
9) Write a Python program to draw 3D Plots using Plotly Libraries.
import numpy as np
import [Link] as plt
from mpl_toolkits.mplot3d import Axes3D
[Link](0)
X = [Link](50)
Y = [Link](50)
Z = [Link](50)
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
[Link](X, Y, Z, c='r', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
[Link]()
OUTPUT:
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
10 (a) Write a Python program to draw Time Series using Plotly Libraries.
import numpy as np
import pandas as pd
import [Link] as plt
# Generate random data
data = [Link](size=365)
# Convert data into a pandas dataframe with a datetime index
index = pd.date_range(start='1/1/2022', periods=365, freq='D')
df = [Link](data, index=index, columns=['Value'])
# Create a figure and axis object
fig, ax = [Link]()
# Plot the data as a line plot
[Link]([Link], df['Value'])
# Set the title and labels
ax.set_title('Time Series Data')
ax.set_xlabel('Date')
ax.set_ylabel('Value')
# Format the x axis as a date axis
ax.xaxis_date()
# Show the plot
[Link]()
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
OUTPUT:
10 (b) Write a Python program for creating Maps using Plotly Libraries.
# Define the size of the map
map_width = 20
map_height = 10
# Create a 2D list to represent the map grid
map_grid = [['.' for _ in range(map_width)] for _ in range(map_height)]
# Define the coordinates of some points of interest
# For simplicity, let's represent them as (x, y) tuples
points_of_interest = [(4, 3), (10, 5), (16, 7)]
# Place markers for the points of interest on the map grid
for point in points_of_interest:
x, y = point
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
if 0 <= x < map_width and 0 <= y < map_height:
map_grid[y][x] = 'X'
# Print the map
print("Simple ASCII Map:")
for row in map_grid:
print(' '.join(row))
Output:
Simple ASCII Map:
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . X . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . X . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . X . . .
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . .
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
Viva Questions
1. Difference between java and python programming language
2. What is Data Visualization
3. What are the Key Features of Python Programming Language
4. What are the applications of Python programming language
5. What are variables? Discuss the steps to use a variable
6. Explain data types in python.
7. Explain input() function in python.
8. Explain min() function
9. What are keywords? How many keywords are there in python
10. Define Fibonacci series.
11. Syntax for defining a function
12. what is function
13. Explain Return statement.
14. Explain Control statements in python
15. Explain what is sep? why is it used.
16. Define What is palindrome sequence
17. Explain Slicing in Python
18. Explain Count() Function
19. What if the function of range() method
20. Strings in python
21. Define what is decimal and Hexadecimal value
22. How do you access elements in a string
23. Explain Split() function in python
Poornamathi, Assistant Professor Dept of CSE, GCEM
DATA VISUALIZATION WITH PYTHON
24. Explain Difflib
25. Why is SequenceMatcher() used and how many arguments one should pass
to SequenceMatcher() function
26. Explain ratio() and round() function
27. Explain Dictionary in python
28. Numpy in python
29. Explain isdigit(), isupper(), islower() functions
30. Use of Sklearn
31. Use of DataFrame
32. Explain usage of hue and palette
33. What do you mean by output_file
34. Use of ColumnDataSource
35. Seed(0) meaning
36. Use of Plotly
37. Explain join () function in python
38. Advantages of using Python Programming
Poornamathi, Assistant Professor Dept of CSE, GCEM
Scikit
Scikit-learn is an open source data analysis library, and the gold standard for Machine Learning
(ML) in the Python ecosystem. Key concepts and features include: Algorithmic decision-making
methods, including: Classification: identifying and categorizing data based on patterns.
Load
load() is used to load arrays or pickled objects from files.
Dataframe
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table
with rows and columns.
Seaborn
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level
interface for drawing attractive and informative statistical graphics.
Hue and palatte
hue' is used to visualize the data of different categories in one plot. 'paltte' is used to change the
colour of the plot.
palette attribute is used to set the color of the bars.
Target
target" is just a variable name. You can use any other variable name instead of "target" and it
won't make any difference.
Bokeh Graph
Bokeh is a Python library that is used to make highly interactive graphs and visualizations. This
is done in bokeh using HTML and JavaScript. This makes it a powerful tool for creating projects,
custom charts, and web design-based applications.
Annotations and legends in python
Legends and annotations are effective tools to display information required to comprehend a plot
in a glance. A typical plot will have the following additional information elements: A legend
describing the various data series in the plot.
ColumnDataSource
The ColumnDataSource is a fundamental data structure of Bokeh. Most plots, data tables, etc. will
be driven by a ColumnDataSource . If the ColumnDataSource initializer is called with a single
argument that can be any of the following: A Python dict that maps string names to sequences of
values, e.g. lists, arrays, etc.
Output_notebook()
output_notebook function that gives us the ability to display Bokeh plots in output cells of Jupyter
notebooks. import [Link] import [Link] import [Link] import numpy as np
import pandas as pd import os bokeh. io. output_notebook()
mpl_toolkits.mplot3d meaning in python
mplot3d. The mplot3d toolkit adds simple 3D plotting capabilities (scatter, surface, line, mesh,
etc.) to Matplotlib by supplying an Axes object that can create a 2D projection of a 3D scene. The
resulting graph will have the same look and feel as regular 2D plots.
Axes3D
An Axes3D object is created just like any other axes using the projection='3d' keyword. Create a
new [Link] and add a new axes to it of type Axes3D : import [Link]
as plt from mpl_toolkits.mplot3d import Axes3D fig = plt. figure() ax = fig.
[Link](0) python
The seed() method is used to initialize the random number generator. The random number
generator needs a number to start with (a seed value), to be able to generate a random number. By
default the random number generator uses the current system time.
add_subplot python
There is an add_subplot() function similar to plt. subplot() under plt. figure() that allows us to
create additional subplots under the same figure.