如何解决在 Python 中绘制多个图形的有效方法
我想知道有没有更有效的方法可以在 Python 中绘制倍数。 例如:
x = np.linspace(0,2*np.pi,100)
y = np.sin(x)
y_shifted = np.sin(x+np.pi)
plt.plot(x,y)
plt.plot(x,y_shifted)
在这里,我们将两个图形叠加在一起。但是首先保存函数的值(例如保存到另一个数组),然后将它们绘制在参数上不是更有效吗?如果是,我们怎么做?
谢谢!
解决方法
我尝试了 furas 建议:
在 100 个数字(每个数字 1k 行)之后,这些是我的结果:
Plot one at a time:
Time to plot: Min: 0.504s,Max: 6.728s,Avg: 0.929s
Time to show: Min: 0.727s,Max: 11.425s,Avg: 1.250s
Plot all at once
Time to plot: Min: 0.341s,Max: 7.839s,Avg: 0.776s
Time to show: Min: 0.724s,Max: 8.165s,Avg: 1.294s
所以……差不多?也许快一点?与运行之间的差异相比,方法之间的差异很小,因此 IMO 不值得担心。如果您的应用程序感觉很慢,这也救不了一天。
要生成的代码:
import numpy as np
from matplotlib import pyplot as plt
from random import uniform
import time
def plot_one_at_a_time():
start = time.time()
x = np.linspace(0,2*np.pi,100)
for i in range(1000):
shift = uniform(0,100)
y_shifted = np.sin(x+shift)
plt.plot(x,y_shifted)
plotdonetime = time.time()
plt.show()
showdonetime = time.time()
plot_times_one.append(plotdonetime-start)
show_times_one.append(showdonetime-plotdonetime)
def plot_at_once():
start = time.time()
x = np.linspace(0,100)
data = []
for i in range(1000):
shift = uniform(0,100)
y_shifted = np.sin(x+shift)
data.append(x)
data.append(y_shifted)
plt.plot(*data)
plotdonetime = time.time()
plt.show()
showdonetime = time.time()
plot_times_all.append(plotdonetime-start)
show_times_all.append(showdonetime-plotdonetime)
plot_times_one = []
show_times_one = []
plot_times_all = []
show_times_all = []
for i in range(100):
plot_one_at_a_time()
plot_at_once()
print("Plot one at a time:")
print("Time to plot: Min: {:.3f}s,Max: {:.3f}s,Avg: {:.3f}s".format(np.min(plot_times_one),np.amax(plot_times_one),np.mean(plot_times_one)))
print("Time to show: Min: {:.3f}s,Avg: {:.3f}s".format(np.min(show_times_one),np.amax(show_times_one),np.mean(show_times_one)))
print()
print("Plot all at once")
print("Time to plot: Min: {:.3f}s,Avg: {:.3f}s".format(np.min(plot_times_all),np.amax(plot_times_all),np.mean(plot_times_all)))
print("Time to show: Min: {:.3f}s,Avg: {:.3f}s".format(np.min(show_times_all),np.amax(show_times_all),np.mean(show_times_all)))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。