Matplotlib programs for practical file
Question1: Plot a line graph to visualize the monthly temperatures in a city for a year. The data
is as follows:
Months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
Temperatures (in °C): [5, 7, 13, 18, 24, 28, 30, 29, 25, 18, 11, 7]
Answer and Output:
import matplotlib.pyplot as plt
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
temperatures = [5, 7, 13, 18, 24, 28, 30, 29, 25, 18, 11, 7]
plt.plot(months, temperatures, marker='o', linestyle='-', color='b')
plt.title('Monthly Temperatures Over a Year')
plt.xlabel('Months')
plt.ylabel('Temperature (°C)')
plt.grid(True)
plt.show()
Question2: Create a bar graph to represent the sales figures of three different products (A, B,
and C) for a store in a month. Colour of the product A,B &C should be represent as green,red
and blue respectively. The data is as follows:
Products: ['A', 'B', 'C']
Sales (in units): [150, 200, 120]
Answer and Output:
import matplotlib.pyplot as plt
products = ['A', 'B', 'C']
sales = [150, 200, 120]
plt.bar(products, sales, color=['g',’r’,’b’])
plt.title('Monthly Sales of Products')
plt.xlabel('Products')
plt.ylabel('Sales (units)')
plt.show()
Question3: Generate a pie chart to visualize the distribution of expenses in a monthly budget.
The data is as follows:
Expense Categories: ['Housing', 'Transportation', 'Food', 'Entertainment', 'Utilities']
Expenses (in $): [1200, 400, 600, 300, 200]
Answer and Output:
import matplotlib.pyplot as plt
categories = ['Housing', 'Transportation', 'Food', 'Entertainment', 'Utilities']
expenses = [1200, 400, 600, 300, 200]
plt.pie(expenses, labels=categories, autopct='%1.1f%%', startangle=140)
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.title('Monthly Budget Distribution')
plt.show()
Question4: Construct a histogram to visualize the distribution of exam scores in a class. The
data is as follows:
Exam Scores: [78, 85, 92, 65, 88, 72, 90, 78, 82, 95, 76, 84, 68, 92, 89, 70, 76, 82, 74, 88]
Answer and Output:
import matplotlib.pyplot as plt
exam_scores = [78, 85, 92, 65, 88, 72, 90, 78, 82, 95, 76, 84, 68, 92, 89, 70, 76, 82, 74, 88]
plt.hist(exam_scores, bins=10, edgecolor='black')
plt.title('Distribution of Exam Scores')
plt.xlabel('Scores')
plt.ylabel('Frequency')
plt.grid(True)
plt.show()