import numpy as np import matplotlib.pyplot as plt stats = [] with open('testdata.csv',…
- User
import numpy as np import matplotlib.pyplot as plt
stats = []
with open('testdata.csv', 'r') as f: data = f.readlines()
for i in data: year, divorces, population, rate_per_thousand = i.split(',')
codestats.append([ int(year), int(divorces), int(population), float(rate_per_thousand) ])for i in stats: fig, axs = plt.subplots(2, 2)
plt.show()
i wanna show the data in subplots, but i don't know how. there's 4 records.
- Assistant
- User
[[2021, 1985072, 331893745, 6.0], [2020, 1676911, 329484123, 5.1], [2019, 2015603, 328239523, 6.1], [2018, 2132853, 327167434, 6.5]]
this is what the stats variable data is.
- Assistant
Given your
statsvariable as an array with those 4 records, you'll want to create a subplot for each element of the statistic (divorces, population, rate_per_thousand) across the different years.Here's what you can do:
python - User
import numpy as np import matplotlib.pyplot as plt
stats = []
with open('testdata.csv', 'r') as f: data = f.readlines()
for i in data: year, divorces, population, rate_per_thousand = i.split(',') stats.append([ int(year), int(divorces), int(population), float(rate_per_thousand) ]) stats.sort(key=lambda x: x[0])
Extract data for plotting
years = [stat[0] for stat in stats] divorces = [stat[1] for stat in stats] populations = [stat[2] for stat in stats] rates_per_thousand = [stat[3] for stat in stats]
Create a figure and 2x2 grid of subplots. figsize can be adjusted as necessary.
fig, axs = plt.subplots(2, 2, figsize=(10, 8))
Flatten axs to easily use a single index to access subplots.
axs = axs.flatten()
Plot divorces
axs[0].plot(years, divorces, 'o-') axs[0].set_title('Divorces over Years') axs[0].set_xlabel('Year') axs[0].set_ylabel('Number of Divorces')
Plot population
axs[1].plot(years, populations, 'o-') axs[1].set_title('Population over Years') axs[1].set_xlabel('Year') axs[1].set_ylabel('Population')
- Assistant
The "half years" on the x-axis are a result of the default behavior of the Matplotlib plotting library when it automatically determines the ticks and labels based on the provided data. If the range of years is small, it may place ticks at non-integer intervals. To ensure that only the full years appear on the x-axis, you can set the ticks manually using the method. Here's how you can modify your code: