Python Code to Plot the Square of Natural Numbers (0-100)
Here's a Python code snippet to create a list 'y' containing the squares of 'x' (natural numbers from 0 to 100) and then plot the line representing the relationship between 'x' and 'y' on a figure. You can customize the plot with different colors, line styles, markers, text, and more.
import matplotlib.pyplot as plt
x = list(range(101))  # Creating a list x with natural numbers from 0 to 100
y = [i ** 2 for i in x]  # Creating a list y containing the squares of numbers in x
plt.figure()  # Creating a new figure
plt.plot(x, y, color='green', linestyle='-', linewidth=2, marker='o', markersize=5)  # Plotting the line connecting (x, y) points with green color, solid line style, and circular markers
plt.title('Plot of y = x^2')  # Setting the title of the figure
plt.xlabel('x')  # Setting the x-axis label
plt.ylabel('y')  # Setting the y-axis label
# Adding text to the figure
plt.text(50, 5000, 'Square of x', fontsize=12, color='blue')  # Adding text 'Square of x' at (50, 5000) with blue color and font size 12
plt.show()  # Displaying the figure
In this code:
- The plotfunction plots the line connecting the points (x, y). You can adjust its color, line style, marker type, and more.
- The title,xlabel, andylabelfunctions set the plot's title and axis labels.
- The textfunction allows you to add text to the figure at specific coordinates with customizable formatting.
Feel free to experiment with different values and options to create visually appealing and informative plots.
原文地址: https://www.cveoy.top/t/topic/V03 著作权归作者所有。请勿转载和采集!