Welcome back to my Python progress tracker, where I document my coding journey and share simple yet effective Python programs. Today, I’m working on a basic program using Matplotlib to generate a line plot and save it as an image file.
Let me walk you through the code, explain how it works, and show the graph that was created as a result.
import matplotlib.pyplot as plt
x_axis = [1, 2, 3, 4]
y_axis = [4, 3, 2, 1]
fig, ax = plt.subplots()
ax.plot(x_axis, y_axis)
fig.savefig("Plots/basic_plot.png")
Code Explanation:
1. Importing Matplotlib Library
import matplotlib.pyplot as plt
The first thing I do is import the matplotlib.pyplot module and save it as plt. This module is necessary for generating visualizations in Python. We use the alias plt to make the code cleaner and more readable.
2. Defining Data for the X and Y Axes
x_axis = [1, 2, 3, 4]
y_axis = [4, 3, 2, 1]
Here, I define two lists: x_axis and y_axis. These lists contain 4 integer values each and will represent the points on the graph. The x_axis values are [1, 2, 3, 4], and the corresponding y_axis values are [4, 3, 2, 1]. So, the line will connect these points.
3. Creating Figure and Axis Objects
fig, ax = plt.subplots()
Next, I use plt.subplots() to create two objects:
- fig (Figure): This represents the entire figure, which can hold multiple plots, titles, and labels.
- ax (Axes): This is the actual plotting area where the graph is drawn.
By calling plt.subplots(), I generate a figure (fig) and a single set of axes (ax) where the plot will be displayed.
4. Plotting the Data on the Graph
ax.plot(x_axis, y_axis)
With the ax.plot() function, I plot the x_axis and y_axis data onto the ax object. The function takes the lists x_axis and y_axis and connects the corresponding points to create a line graph.
5. Saving the Graph as an Image
fig.savefig("Plots/basic_plot.png")
Finally, I use the fig.savefig() function to save the generated plot as an image. In this case, the plot is saved as basic_plot.png in the Plots folder. This allows me to keep a permanent record of the graph for future reference.
Graph Output:
Conclusion
This simple program showcases how easy it is to create basic line plots using Matplotlib in Python. As I continue to progress, I’ll keep exploring more advanced plotting techniques and customizations. Feel free to follow me on GitHub and Twitter for more updates on my Python coding journey and visualizations.
- Github: My Github Account
- Twitter: My Twitter Account
I regularly update my projects and share useful tips for developers at every level. Thanks for reading! Stay tuned for more Python projects and code snippets.