Python Matplotlib Plot: Sin(x) & Cos(x) with Labels & Ticks
Plotting Sin(x) and Cos(x) with Python Matplotlib
This guide provides a step-by-step approach to plotting trigonometric functions like sin(x)
and cos(x)
using Python's powerful Matplotlib library. We'll cover generating data, plotting lines, adding labels, customizing ticks, and more.pythonimport matplotlib.pyplot as pltimport numpy as np
Generate datax = np.linspace(0, 2 * np.pi, 100)data1 = np.sin(x)data2 = np.cos(x)
Create a figureplt.figure()
Plot data with labels and colorsplt.plot(x, data1, color='blue', label='data1 = sin(x)')plt.plot(x, data2, color='red', label='data2 = cos(x)')
Set title and axis labelsplt.title('Trigonometric Functions')plt.xlabel('x')plt.ylabel('y')
Add legendplt.legend(loc='upper right')
Set axis limitsplt.xlim(0, 2 * np.pi)plt.ylim(-1, 1)
Customize ticksplt.xticks(np.arange(0, 2.5 * np.pi, np.pi / 2), ['0', 'π/2', 'π', '3π/2', '2π'])plt.yticks(np.arange(-1, 1.1, 0.5))
Add labels on top of linesplt.text(x[30], data1[30], 'sin(x)', color='blue', ha='center', va='bottom')plt.text(x[70], data2[70], 'cos(x)', color='red', ha='center', va='top')
Display the plotplt.show()
Explanation:
- Import Libraries: We start by importing
matplotlib.pyplot
(for plotting) andnumpy
(for numerical operations).2. Generate Data:np.linspace
creates a list of 100 evenly spaced values between 0 and 2π. We then calculatesin(x)
andcos(x)
using NumPy's trigonometric functions.3. Create Figure:plt.figure()
initiates a new figure for our plot.4. Plot Lines:plt.plot
is used to plot our data. We specify colors and labels for each line.5. Labels and Title: We set the plot title, x-axis label, and y-axis label for clarity.6. Legend: The legend is added usingplt.legend
and placed in the upper right corner.7. Axis Limits:plt.xlim
andplt.ylim
control the range of values displayed on the x and y axes.8. Custom Ticks:plt.xticks
andplt.yticks
allow precise control over tick locations and labels.9. Labels on Lines:plt.text
adds text labels directly on top of the lines for better visualization.10. Display Plot: Finally,plt.show()
displays the generated plot.
This comprehensive guide demonstrates how to create visually appealing and informative plots of trigonometric functions using Python and Matplotlib. You can easily adapt this code to visualize other functions or data by modifying the data generation and plotting parameters.
原文地址: http://www.cveoy.top/t/topic/V5W 著作权归作者所有。请勿转载和采集!