Lab 13: Fun with Matplotlib | CMSC 105 Elementary Programming - Fall 2024

Lab 13: Fun with Matplotlib

temperature.py

''' 
Author name: <Your name here>
This program will plot temperature data from a file.
'''

import matplotlib.pyplot as plt

# Read data from the file
with open("temperature_data.txt", "r") as file:
    years = []
    temperatures = []
    for line in file:
        year, temp = line.strip().split(",")
        years.append(int(year))
        temperatures.append(float(temp))

# Create the line chart
plt.plot(years, temperatures)

# Label each axis and give the plot a title
plt.xlabel('Year')
plt.ylabel('Temperature')
plt.title('Temperature Trends')

# Display the plot
plt.show()

Program 2: Olympic Medals

medals.py

''' 
Author name: <Your name here>
This program will plot olympic medal counts from a file.
'''

import matplotlib.pyplot as plt

with open("olympic_medals.txt", "r") as file:
    # Create an empyt dictionary
    medal_count_dictionary = {}
    
    for line in file:
        # The strip() method removes any leading, and trailing whitespaces.
        # The split() method splits a string into a list.
        # The following line of code will split the line of text into a two item list.
        # The first item in the list is the country name
        # The second item in the list is the medal count for that country
        split_list = line.strip().split(",")
        
        # Put each country into the dictionary as a key,
        # with the medal count as the value.
        medal_count_dictionary[split_list[0]] = int(split_list[1])

# Create a new bar plot for each country
# For each country in the medal count dictionary.
# Add a new bar to the bar chart.
for country in medal_count_dictionary:
    plt.bar(country, medal_count_dictionary[country])

# Label the axes and assign a title
plt.xlabel('Countries')
plt.ylabel('Medals')
plt.title('Olympic Gold Medals')

plt.show()

Program 3: Shooting Stars

star.py

''' 
Author name: <Your name here>
This program will plot star data with Matplotlib.
'''

import matplotlib.pyplot as plt

# Read data from the file
with open("star_data.txt", "r") as file:
    brightness = []
    distances = []
    for line in file:
        bright, distance = line.strip().split(",")
        brightness.append(float(bright))
        distances.append(float(distance))

# Create the scatter plot
plt.scatter(distances, brightness, c=brightness)
plt.xlabel("Distance from Earth (light-years)")
plt.ylabel("Brightness (magnitude)")
plt.title("Star Brightness vs. Distance")
plt.colorbar(label="Brightness Scale")
plt.show()