【问题标题】:Making Multiple Figures From the Same Plot从同一个图中制作多个图形
【发布时间】:2020-10-19 20:49:56
【问题描述】:

我有一个需要大量计算才能生成的图(条形图有许多类似于下面的条形图)。我希望将该直方图与其他易于计算且快速计算的函数进行对比,因此这些数字将是函数 + 直方图。

图 1 => 条形图 + 函数 A

图 2 => 条形图 + 函数 B

这是否可以以某种方式保存条形图或数据并为不同的图重新渲染它,而无需重新运行plt.hist

import numpy as np
import matplotlib.pyplot as plt
import math

t = np.linspace(0, 2*math.pi, 400)
a = np.sin(t)
b = np.cos(t)

plt.hist(t,bins=1000,cumulative=False,bottom=True)
plt.plot(t, a, 'r') # plotting t, a separately 
plt.show()

plt.plot(t,b,'r')
plt.hist(t,bins=1000,cumulative=False,bottom=True)
plt.show()

【问题讨论】:

  • 是的,plt.hist 返回一个元组 histograms, bins, patches,您可以捕获并重用它。

标签: python matplotlib


【解决方案1】:

按照@Quang Hoang 的建议保存直方图的绘图数据并使用条形而不是 hist 绘制图表,从而提高速度

代码:

import numpy as np
import matplotlib.pyplot as plt
import math
import time

t = np.linspace(0, 2*math.pi, 400)
a = np.sin(t)
b = np.cos(t)

histograms, bins, patches = plt.hist(t,bins=1000,cumulative=False,bottom=True)

#%%Classic
start = time.time()
plt.hist(t,bins=1000,cumulative=False,bottom=True)
plt.plot(t, a, 'r') # plotting t, a separately 
plt.show()


plt.hist(t,bins=1000,cumulative=False,bottom=True)
plt.plot(t,b,'r')
plt.show()

print(time.time()-start)
#%%Bar + Data

start = time.time()
plt.bar(x=bins[:-1], height=histograms,bottom=True,width=0.0075)
plt.plot(t, a, 'r') # plotting t, a separately 
plt.show()

plt.plot(t,b,'r')
plt.bar(x=bins[:-1], height=histograms,bottom=True,width=0.0075)
plt.show()
print(time.time()-start)

结果:

3.838867425918579
2.840409278869629

【讨论】:

  • width=0.0075 来自哪里?为什么不使用patches
  • 真的不知道补丁是什么,需要校准宽度,想不出自动化的方法来实现它...如果你想到了什么,请告诉我
  • 我相信我发现这个答案很有帮助,我在我的代码中使用了它,它将速度提高了 100 倍 stackoverflow.com/questions/35738199/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-24
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多