1

I have a plot that requires a lot of computation to generate (bar chart with many bins similar to the one below). I want to have that histogram plotted against other functions that are easy and fast to compute, so the figures would be function + histogram.

Figure 1 => Bar + function A

Figure 2 => Bar + function B

Is this possible to save the bar plot or data somehow and re-render it for different plots, without re-running 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()
Kaleb
  • 25
  • 1
  • 4

1 Answers1

0

Managed to increase the speed by saving the plotting data of a histogram as @Quang Hoang suggested and plotting the charts with bar, instead of hist

code:

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)

Results:

3.838867425918579
2.840409278869629
Kaleb
  • 25
  • 1
  • 4
  • Where does `width=0.0075` come from? Why don't you have an use for the `patches`? – gboffi Oct 20 '20 at 07:21
  • really didn't know what patches is, needed to calibrate the width, couldn't think of an automated way to have that... if you think of something do let me know – Kaleb Oct 20 '20 at 07:59
  • I believe I found this answer to be helpful which I used in my code, which improved the speed by 100 folds https://stackoverflow.com/questions/35738199/matplotlib-pyplot-hist-very-slow – Kaleb Oct 20 '20 at 16:32