Python for Data Science: Chapter 6: Data Visualization

Matplotlib: Python Programming Exercises

Python open source drawing library

Matplotlib - Data Visualization : Python Programming Exercises - Example Problems and Solution

Matplotlib: Python Programming Exercises

 

Example:1

Write a Python programming to display a bar chart of the popularity of mobile phone brands.

Sample data:

Mobile phone brands: Apple, OnePlus, Samsung, OPPO, VIVO, Xiaomi

Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7

Solution :

import matplotlib.pyplot as plt

x = ['Apple', 'OnePlus', 'Samsung', 'OPPO', 'ViVo', 'Xiaomi']

popularity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]

x_pos = [i for i, in enumerate(x)]

plt.bar(x_pos, popularity, color='blue')

plt.xlabel("Mobile Brands")

plt.ylabel("Popularity")

plt.title("Popularity of Mobile Phones \n")

plt.xticks(x_pos, x)

# Turn on the grid

plt.minorticks_on()

plt.grid(which='major', linestyle='‒', linewidth='0.5', color='red')

# Customize the minor grid

plt.grid(which='minor', linestyle=':, linewidth='0.5', color='black')

plt.show()

Output

Popularity of Mobile Phones


 

Example:2

Write a Python code snippet to create bar plot from a DataFrame.

Sample DataFrame:

a b c d e

2 ,4,8,5,7,6

4 2,3,4,2,6

6,4,7,4,7,8

8 2,6,4,8,6

10 2,4,3,3,2

Solution:

import pandas as pd

import matplotlib.pyplot as plt

import numpy as np

a=np.array([[4,8,5,7,6], [2,3,4,2,6],[4,7,4,7,8],[2,6,4,8,6], [2,4,3,3,2]])

df=pd.DataFrame(a, columns=['a', 'b','c','d', 'e'], index=[2,4,6,8,10])

df.plot(kind='bar')

plt.show()

Output


 

Example:3

Write a Python code snippet to plot two or more lines with different styles.

Solution :

import matplotlib.pyplot as plt

# line 1 points

x1 = [10,20,30]

y1 = [30,50,20]

# line 2 points

x2 = [10,20,30]

y2 = [30,10,20]

# Set the x axis label of the current axis.

plt.xlabel('x‒axis')

# Set the y axis label of the current axis.

plt.ylabel('y‒axis')

# Plot lines and/or markers to the Axes.

plt.plot(x1,y1, color='green', linewidth = 4, label= 'dotted_line',linestyle='dotted')

plt.plot(x2,y2, color='blue', linewidth 6, label = 'dashed_line', linestyle='dashed')

# Set a title

plt.title("Demonstrating Different Line Styles")

# show a legend on the plot

plt.legend()

# function to show the plot

plt.show()

Output

Demonstrating Different Line Styles


 

Example:4

Write a Python code snippet to create sine and cosine wave in the same plot.

Solution :

import matplotlib.pyplot as plt

import numpy as np

# Using Numpy to create an array X

np.arange(0, np.pi*3, 0.1)

# Assign variables to the y axis part of the curve

y = np.sin(x)

z = np.cos(x)

plt.plot(x, y, color='r', label='sin')

plt.plot(x,z, color='b', label='cos')

plt.xlabel("Angle")

plt.ylabel("Magnitude")

plt.title("Sine and Cosine Waves")

# Adding legend, to recognize the curve according to it's color

plt.legend()

plt.show()

Output

Sine and Cosine Waves


 

Example:5

Write a Python code snippet to plot a stacked bar chart.

Solution :

import matplotlib.pyplot as plt

labels = ['India', 'Japan', 'US', 'UK']

men = [25, 32, 30, 35]

women = [20, 35, 32, 38]

plt.bar(labels, men, color='b', label='Men')

plt.bar(labels, women, color='r', bottom=men, label='Women')

plt.legend()uster

plt.show()

Men

Output


 

Example:6

Write a Python code snippet to plot a horizontal bar chart.

Solution :

import matplotlib.pyplot as plt

labels = ['one', 'two', 'three', 'four']

values = [10, 20, 30, 40]

plt.barh(labels, values)

plt.show()


 

Example:7

How can you set a logarithmic scale for a plot in Matplotlib?

Solution:

In Matplotlib, you can set a logarithmic scale for either the x‒axis, y‒axis or both using the semilogx(), semilogy() and loglog() functions respectively. We can also set the scale of an axis to log scale by calling xscale and yscale. These functions plot data in logarithmic scales which are useful when dealing with exponential growth or decay. For example ‒

import matplotlib.pyplot as plt

# exponential function x = 10^y

x = [ 10**i for i in range(5)]

y = [i for i in range(5)]

#convert x‒axis to Logarithmic scale

plt.xscale("log")

plt.plot(x,y)

Output


 

Example:8

Write a Python program to draw a scatter plot comparing two subject marks of Mathematics and Science. Use marks of 10 students.

Test data:

math_marks = [50, 67, 90, 81, 98, 40, 60, 67, 100, 45]

science_marks = [35, 46, 72, 45, 95, 88, 32, 54, 18, 44]

marks_range=[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Solution:

import matplotlib.pyplot as plt

import pandas as pd

math_marks = [50, 67, 90, 81, 98, 40, 60, 67, 100, 45]

science marks = [35, 46, 72, 45, 95, 88, 32, 54, 18, 44]

 marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

plt.scatter(marks_range, math_marks, label='Math marks')

plt.scatter(marks_range, science_marks, label='Science marks')

plt.title('Mathematics and Science Marks Comparison')

plt.xlabel('Range of Marks')

plt.ylabel('Marks Obtained')

plt.legend()

plt.show()

Output


 

Example:9

How to overplot a line on scatter plot in Python. Illustrate with code.

Solution :

import matplotlib.pyplot as plt

import numpy as np

# Sample data for scatter plot

x = np.array([1, 2, 3, 4, 5])

y = np.array([2, 3, 4, 5, 3.5])

# Generate random values for line plot

np.random.seed(0) # Set seed for reproducibility

x line = np.random.rand(30) * 5 # Random values between 0 and 5

x_line = np.sort(x_line)

y_line = np.random.rand(30) * 10 # Random values between 0 and 10

plt.scatter(x, y, color="blue')

plt.plot(x_line, y_line, color='red')

plt.xlabel('X axis')

plt.ylabel('Y axis')

plt.title('Scatter Plot with Overplotted Line')

plt.show()

Output

Scatter Plot with Overplotted Line


Code explanation: In above code,

• The scatter plot is generated for the values ‒

o x = np.array([1, 2, 3, 4, 5])

o y = np.array([2, 3, 4, 5, 3.5])

•  The line plot is generated for the values ‒

o np.random.rand(30) * 5 generates 30 random values between 0 and 5 for x_line.

o np.random.rand(30) * 10 generates 30 random values between 0 and 10 for y_line.

o np.sort(x_line) sorts the x_line array to ensure a smooth line plot.

• The color of line plot is red and the scatter plot points are blue in color.

 

Python for Data Science: Chapter 6: Data Visualization : Tag: Computer Programming, Python, Data Science : Python open source drawing library - Matplotlib: Python Programming Exercises


Python for Data Science: Chapter 6: Data Visualization



Under Subject


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation



Related Subjects


English Essentials II

EN25C02 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation



Linear Algebra

MA25C02 2nd Semester | 2025 Regulation


Applied Physics (CSIE) II

PH25C03 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Digital Principles and Computer Organization

CS25C06 2nd Semester AIDS, CSE, IT, CSE(CY) Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Basic Electrical and Electronics Engineering

EE25C01 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation


Re-Engineering for Innovation

ME25C05 2nd Semester | 2025 Regulation | 2nd Semester 2025 Regulation


Python for Data Science - Laboratory

AD25201 2nd Semester AIDS Dept | 2025 Regulation | 2nd Semester 2025 Regulation