plot year on year values in a single plot in matplotlib in python

To plot year on year values in a single plot using Matplotlib in Python, you can follow these steps:

  1. Import the necessary libraries:
main.py
import matplotlib.pyplot as plt
import datetime
48 chars
3 lines
  1. Create your data:
main.py
# Example data for year on year values
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020]
values = [4, 7, 9, 11, 13, 15, 14, 12, 10, 8, 6]
163 chars
4 lines
  1. Convert the years to datetime objects:
main.py
dates = [datetime.datetime(year, 1, 1) for year in years]
58 chars
2 lines
  1. Plot the data:
main.py
plt.plot(dates, values)
24 chars
2 lines
  1. Customize the plot as needed:
main.py
plt.xlabel('Year')
plt.ylabel('Values')
plt.title('Year on Year Values')
plt.grid(True)
88 chars
5 lines
  1. Display the plot:
main.py
plt.show()
11 chars
2 lines

Here's the complete example code:

main.py
import matplotlib.pyplot as plt
import datetime

# Example data for year on year values
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020]
values = [4, 7, 9, 11, 13, 15, 14, 12, 10, 8, 6]

dates = [datetime.datetime(year, 1, 1) for year in years]

plt.plot(dates, values)

plt.xlabel('Year')
plt.ylabel('Values')
plt.title('Year on Year Values')
plt.grid(True)

plt.show()
397 chars
18 lines

By converting the years to datetime objects, we can have the x-axis represent the years in a more meaningful way rather than just discrete values. The plt.plot function is used to create the line plot, and then you can customize the plot by adding labels, titles, and a grid. Finally, plt.show() is used to display the plot.

gistlibby LogSnag