python - 如何生成最多 10 次迭代的随机折线图?
问题描述
我已经完成了一个图的编码,如何使用相同的代码随机生成 10 个图。我想要一个独特的图表。
import matplotlib.pyplot as plt
# line 1 points
x1 = [1,2,3]
y1 = [2,4,1]
# plotting the line 1 points
plt.plot(x1, y1, label = "line 1")
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Two lines on same graph!')
# show a legend on the plot
plt.legend()`enter code here`
# function to show the plot
plt.show()
解决方案
如果我没记错的话,你只需要 10 个带有随机线条的图表。
从您的示例中,我假设您只需要整数值。
使用Numpy可以生成随机值列表。在以下示例中,数组的长度为 10,值范围为 0 到 15。
import numpy as np
x = np.random.randint(low=0, high=15, size=10)
y = np.random.randint(low=0, high=15, size=10)
我不明白你是否还要求这个数组是不同的。
让我们继续绘制 10 个随机图:
import matplotlib.pyplot as plt
def draw_plot(sub):
"""Draw a random graph."""
# line 1 points
x = np.sort(np.random.randint(low=0, high=15, size=10))
y = np.random.randint(low=0, high=15, size=10)
# plotting the line 1 points
sub.plot(x, y, label = "line 1")
# naming the x axis
sub.set_xlabel('x - axis')
# naming the y axis
sub.set_ylabel('y - axis')
# giving a title to my graph
sub.set_title('Two lines on same graph!')
# show a legend on the plot
sub.legend()
plt.figure(figsize=(20, 8))
for i in range(10):
sub = plt.subplot(2, 5, i+1)
draw_plot(sub)
plt.show()
推荐阅读
- python - 使用 python 获取机器学习算法的所有超参数列表
- gitlab - 通过 Gitlab YML Job 验证 XML 或 JSON Schema
- python - 使用 Python、Numpy 和 Scikit-Image/OpenCV 根据中间分水线的长度合并图像段
- javascript - onclick 不适用于 javascript 中相同功能的两个或多个链接
- javascript - 如何使用 jest 在 typescript 中测试抽象类?
- php - 在 laravel 中获取原始 sql 查询
- python - 在 Python 中使用请求的不完整下载
- android - 处理应用程序内部的深层链接后,将用户重定向回浏览器
- python-3.x - 在 tkinter 中显示文本列表
- django - 如何访问在占位符字段中创建的 cms 插件