如何修改代码可以将平均价格打印到图表中?
import matplotlib.pyplot as plt
# Create a list of prices
prices = [10, 12, 15, 18, 21]
# Calculate the average price
average_price = sum(prices) / len(prices)
# Create a line plot of the prices
plt.plot(prices)
# Add a label to the plot
plt.xlabel("Price")
plt.ylabel("Price")
plt.title("Price vs. Price")
# Show the plot
plt.show()
To print the average price on the chart, we can use the plt.text()
function. Here's an updated code with the plt.text()
function:
import matplotlib.pyplot as plt
# Create a list of prices
prices = [10, 12, 15, 18, 21]
# Calculate the average price
average_price = sum(prices) / len(prices)
# Create a line plot of the prices
plt.plot(prices)
# Add labels to the x and y axes
plt.xlabel("Price")
plt.ylabel("Price")
# Add a text label to the average price
plt.text(average_price, 15, f"Average Price: {average_price}", fontsize=12)
# Show the plot
plt.show()
```