Python Matplotlib Line Plotting Tutorial: Creating Customized Line Graphs
Creating Customized Line Graphs with Matplotlib and Python
This tutorial demonstrates how to create customized line plots in Python using the Matplotlib library. We'll cover the basics of plotting lines with different markers, styles, and colors, as well as adding labels, legends, and adjusting axis limits.
Let's dive into a practical example:pythonimport matplotlib.pyplot as plt
Sample dataa = [1, 2, 3, 2, 1]b = [2, 2, 2, 2, 2]
Create a new figureplt.figure()
Plot line 'a' with red circles and a dashed lineplt.plot(a, 'ro--', label='line 1')
Plot line 'b' with blue asterisks and a dash-dot lineplt.plot(b, 'b*-.', label='line 2')
Set y-axis labelplt.ylabel('Some Numbers')
Set figure titleplt.title('Example Line Plot')
Add a legend (location: upper right, font size: 12, default marker size)plt.legend(loc='upper right', fontsize=12, markerscale=1)
Set x-axis and y-axis limitsplt.axis([-1, 5, 0, 6])
Display the figureplt.show()
Explanation:
- Import Matplotlib: We begin by importing the
matplotlib.pyplot
module asplt
.2. Prepare Data: Define your data points for the lines. Here, we use two lists,a
andb
.3. Create Figure:plt.figure()
creates a new figure window for the plot.4. Plot Lines: We useplt.plot()
to plot the lines: -plt.plot(a, 'ro--', label='line 1')
: Plots line 'a' with red circles ('ro--'
) as markers and a dashed line style. Thelabel
argument sets the label for the legend. -plt.plot(b, 'b*-.', label='line 2')
: Plots line 'b' with blue asterisks ('b*-.')
and a dash-dot line style.5. Labels and Title: -plt.ylabel('Some Numbers')
: Sets the label for the y-axis. -plt.title('Example Line Plot')
: Sets the title of the plot.6. Legend: -plt.legend(loc='upper right', fontsize=12, markerscale=1)
: Adds a legend to the figure. Theloc
argument specifies the location,fontsize
controls the font size, andmarkerscale
adjusts the marker size in the legend.7. Axis Limits: -plt.axis([-1, 5, 0, 6])
: Sets the x-axis limits from -1 to 5 and y-axis limits from 0 to 6.8. Display Plot: -plt.show()
: Displays the plot with all the customizations.
This tutorial provides a basic framework for generating customized line plots with Matplotlib. Experiment with different markers, line styles, colors, and explore the vast capabilities of Matplotlib to create visually appealing and informative graphs for your data.

原文地址: http://www.cveoy.top/t/topic/V4H 著作权归作者所有。请勿转载和采集!