Matplotlib Examples
Problem 1: Create two lists of data: days containing the numbers 1 through 5, and temperature containing the values 70, 72, 68, 75, and 74. Create a basic line plot showing the temperature over these days.
matplotlib-exercises.py
import matplotlib.pyplot as plt
# 1. Create the data
days = [1, 2, 3, 4, 5]
temperature = [70, 72, 68, 75, 74]
# 2. Create the line plot
plt.plot(days, temperature)
# 3. Display the plot
plt.show()
Problem 2: Create a scatter plot using two lists of coordinates. Make the data points red. Add a title to the chart, an X-axis label, and a Y-axis label so the viewer knows what they are looking at.
matplotlib-exercises.py
import matplotlib.pyplot as plt
# 1. Create the data
height = [60, 62, 65, 68, 70, 74]
weight = [110, 120, 140, 160, 170, 190]
# 2. Create a scatter plot and change the color
plt.scatter(height, weight, color='red')
# 3. Add context (Title and Labels)
plt.title("Height vs. Weight")
plt.xlabel("Height (inches)")
plt.ylabel("Weight (lbs)")
# 4. Display the plot
plt.show()
Problem 3: You have a dictionary containing sales data for three different products (Apples: 35, Bananas: 50, Oranges: 20). Extract the product names and their sales, and plot them as a bar chart.
matplotlib-exercises.py
import matplotlib.pyplot as plt
# 1. Create the data
sales_data = {'Apples': 35, 'Bananas': 50, 'Oranges': 20}
# Extract keys (categories) and values (heights)
products = list(sales_data.keys())
sales = list(sales_data.values())
# 2. Create the bar chart
plt.bar(products, sales)
# 3. Add a title
plt.title("Fruit Sales This Week")
# 4. Display the plot
plt.show()