When I run my code I create a figure, then I create a subplot in that figure. Then when I try to add a title to it using ax.set_title("title") it sometimes shows up for a split second then goes away. I have tried using plot.title aswell with no luck.
I tried recreating the error in a small example but for some reason it worked just fine there, so here is the entire source code of the code.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.style as style
import plotgen
from matplotlib.widgets import Button
class plotWindow():
def __init__(self):
style.use("bmh")
self.dp = 30
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1, 1, 1, label="ax1")
self.cax = 1
self.maxax = 2
self.minax = 1
plotgen.clear("plot1.txt")
plotgen.clear("plot2.txt")
axnext = plt.axes([0.80, 0.01, 0.06, 0.06])
axprev = plt.axes([0.73, 0.01, 0.06, 0.06])
bnext = Button(axnext, 'Next >')
bnext.on_clicked(self.changePlotNext)
bprev = Button(axprev, "< Previous")
bprev.on_clicked(self.changePlotPrev)
ani = animation.FuncAnimation(self.fig, self.animate, interval=500)
plt.show()
def changePlotNext(self, i):
if self.cax < self.maxax:
self.cax += 1
self.ax.set_title("Pump " + str(self.cax))
def changePlotPrev(self, i):
if self.cax > self.minax:
self.cax -= 1
self.ax.set_title("Pump " + str(self.cax))
def animate(self, i):
if self.cax == 1:
plotgen.generate("plot1.txt")
graph_data = open('plot1.txt', 'r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x, y = line.split(',')
xs.append(x)
ys.append(float(y))
self.ax.clear()
lx = len(xs)
ly = len(ys)
if len(xs) < self.dp:
pxs = xs
pys = ys
else:
pxs = xs[(lx - (self.dp - 1)):(lx - 1)]
pys = ys[(ly - (self.dp - 1)):(ly - 1)]
self.ax.plot(pxs, pys, "r")
elif self.cax == 2:
plotgen.generate("plot2.txt")
graph_data = open('plot2.txt', 'r').read()
lines = graph_data.split('\n')
xs = []
ys = []
for line in lines:
if len(line) > 1:
x, y = line.split(',')
xs.append(x)
ys.append(float(y))
self.ax.clear()
lx = len(xs)
ly = len(ys)
if len(xs) <= self.dp:
pxs = xs
pys = ys
else:
pxs = xs[(lx - (self.dp - 1)):(lx - 1)]
pys = ys[(ly - (self.dp - 1)):(ly - 1)]
self.ax.plot(pxs, pys)
plotWindow()
As you can see in my changePlotNext and changePlotPrev functions I'm trying to change the title. Sometimes they display for a split second when I change, but then it goes away. And I am very aware that I have not set a title to display before I change the plot.
In animate, you have self.ax.clear(), which is removing all artists, texts, etc. on the Axes, including the title.
A simple option, then, is to reset the title after you clear the axes. So if you add:
self.ax.set_title("Pump " + str(self.cax))
in both places, immediately after you call self.ax.clear(), your titles will still be shown.
Another option would be to stop clearing the axes, but just remove the items you need to remove. I think this is just the lines you have plotted? So, for example, you could remove the call to self.ax.clear(), and add:
for line in self.ax.lines:
line.remove()
in its place. That will remove just the plotted line, but retain the title.
Related
I got a .fig file generated in Matlab and I would like to display it in python environment, or at least retrieve the data. It works well when the original figure does not contain error bars. But when I have error bars then it looks like a staircase. Any ideas on how I could fix it?
The code I have been using is this:
## escape disti time for ions ##
size_f =26
def plotFig(filename,fignr=1):
from scipy.io import loadmat
from numpy import size
from matplotlib.pyplot import plot,figure,xlabel,ylabel,show,clf,xlim,ylim,legend,yticks,xticks
d = loadmat(filename,squeeze_me=True, struct_as_record=False)
ax1 = d['hgS_070000'].children
if size(ax1) > 1:
legs= ax1[1]
ax1 = ax1[0]
else:
legs=0
figure(fignr)
clf()
#hold(True)
counter = 0
counter1 =0
# x=np.zeros((1000,1000))
#y=np.zeros((1000,1000))
for line in ax1.children:
if line.type == 'graph2d.lineseries':
if hasattr(line.properties,'Marker'):
mark = "%s" % line.properties.Marker
mark = mark[0]
else:
mark = '.'
if hasattr(line.properties,'LineStyle'):
linestyle = "%s" % line.properties.LineStyle
else:
linestyle = '-'
if hasattr(line.properties,'Color'):
r,g,b = line.properties.Color
else:
r = 0
g = 0
b = 1
if hasattr(line.properties,'MarkerSize'):
marker_size = line.properties.MarkerSize
else:
marker_size = 1
#if counter1 ==0:
x = line.properties.XData
y = line.properties.YData
#counter1=1
#else:
# x1 = line.properties.XData
# y1 = line.properties.YData
if counter ==0:
x = line.properties.XData
y = line.properties.YData
plt.plot(x[y>0],y[y>0],linestyle=linestyle,linewidth=3.0)
counter=1
elif counter==1:
x1 = line.properties.XData
y1 = line.properties.YData
#plt.plot(x1[y1>0],y1[y1>0],linestyle=linestyle,linewidth=3.0)
counter=2
else:
x = line.properties.XData
y = line.properties.YData
plt.plot(x[y>0],y[y>0],linestyle=linestyle,linewidth=4.0,color=[r,g,b])
plt.yscale('log')
plt.xscale('log')
elif line.type == 'text':
if counter < 1:
xlabel(r'$%s$' % line.properties.String,fontsize =18)
#xlabel('%s' % line.properties.String,fontsize = 18)
counter += 1
elif counter < 2:
ylabel(r'$%s$' % line.properties.String,fontsize = 18)
# ylabel('%s' % line.properties.String,fontsize = 18)
counter += 1
ylim(1e-7,1e-1)
#ylim(ax1.properties.YLim)
xlim((1e-2, 1e3))
plt.rcParams["figure.figsize"] = [10,8]
plt.tick_params(axis='x',labelsize=size_f)
plt.tick_params(axis='y',labelsize=size_f)
plt.ylabel(r'$p(t_{esc})$', fontsize=size_f)
plt.xlabel(r'$t_{esc} \ [sec]$', fontsize=size_f)
#plt.savefig(r'C:\Users\nikos.000\vlahos\png\escape distr_elec.png', format='png',dpi=300)#,bbox_inches='tight')
#plt.savefig(r'C:\Users\nikos.000\vlahos\eps\escape_distr_elec.eps', format='eps',dpi=300)#,bbox_inches='tight')
#### Set tick size ####
labels = [r'$10^{-2}$', r'$10^{-1}$',r'$10^{0}$',r'$10^{1}$',r'$10^{2}$', r'$10^{3}$']#,r'$10^{2}$',r'$10^{4}$']
x = [1e-2,1e-1,1e0,1e1,1e2,1e3]
plt.tick_params(axis='x',labelsize=size_f)
plt.tick_params(axis='y',labelsize=size_f)
plt.xticks(x, labels)
labels1 = [r'$10^{-6}$', r'$10^{-4}$', r'$10^{-2}$']
y = [1e-6,1e-4, 1e-2,]
plt.yticks(y, labels1)
if legs:
leg_entries = tuple(legs.properties.String)
py_locs = ['upper center','lower center','right','left','upper right','upper left','lower right','lower left','best']
MAT_locs=['north','south','east','west','northeast', 'northwest', 'southeast', 'southwest','best']
Mat2py = dict(zip(MAT_locs,py_locs))
location = legs.properties.Location
leg1=legend(leg_entries,loc=Mat2py[location],frameon=False,fontsize=size_f)
leg1.legendHandles[1].set_color('black')
#plt.xticks(fontsize=18 )
#plt.yticks(fontsize=18)
#### Save figure ####
plt.savefig(r'C:\Users\nikos.000\vlahos\png\escape distr_prot.png', format='png',dpi=300,bbox_inches='tight')
plt.savefig(r'C:\Users\nikos.000\vlahos\eps\escape_distr_prot.eps', format='eps',dpi=300,bbox_inches='tight')
show()
return
plotFig(r'C:\Users\nikos.000\neutrons\f5b P=1.fig',fignr=1)
This is how the figure looks:
The original .fig file can be found here:
https://www.dropbox.com/sh/iddxpfvxz85abci/AAAU9p0DM5OYtpI7mE-nLAuga?dl=0
I'm getting confused with the FuncAnimation method. I was trying to show real-time sensor data on my raspberry pi using GPIOs. I set the x range to 100. When my data frames are over 100, I will only pick the recent 100 frames to show. At the beginning when the number of frames is less than 100, the pic shows correctly. The problem is that when frames are over 100, the later pic will overlap with the former pic and the graph just mess up. Here's the beginning graph and the overlap graph.
enter image description here
enter image description here
I checked the matplotlib API and I changed the param "blit" from True to False.
The overlap disappears but the frame rate is becoming too low.
Since I also used FuncAnimation with blit set True in another code and the overlap didn't appear, I guess there something else wrong.
The overlap code is below:
max_limit = 20
fig, ax = plt.subplots(light_num, 1)
data = []
lines = []
for i in range(light_num):
data.append([])
ln_one_light, = ax[i].plot([], [], 'r-')
lines.append(ln_one_light)
def init():
for i in range(light_num):
ax[i].set_xlim(0, max_limit)
ax[i].set_ylim(lower_bound, upper_bound)
return lines
def update(frame):
# print(frame)
global data
for i in range(light_num):
data[i].append(frame[i])
if len(data[i]) > max_limit:
data[i] = data[i][1:]
time_axis = np.arange(len(data[i]))
for i in range(light_num):
# print(time_axis, data[i])
lines[i].set_data(time_axis, data[i])
return lines
def gen_function():
res_array = []
output_string = ''
for i in range(light_num):
val = GPIO.input(light_io_array[i])
res_array.append(val)
output_string = output_string + str(val) + ' '
# print(res_array)
lights_data_writer.update_data(output_string)
yield res_array
ani = FuncAnimation(fig, update, frames=gen_function, interval = 500, repeat = True,
init_func=init, blit=True)
plt.show()
The code that I used with blit set as True, but no overlap happens:
fig, ax = plt.subplots(3, 1)
data_x, data_y, data_z = [], [], []
ln_x, = ax[0].plot([], [], 'r-')
ln_y, = ax[1].plot([], [], 'r-')
ln_z, = ax[2].plot([], [], 'r-')
def init():
for i in range(3):
ax[i].set_xlim(0, 100)
ax[i].set_ylim(-5, 5)
return (ln_x, ln_y, ln_z)
def update(frame):
(x, y, z) = frame
global data_x, data_y, data_z
data_x.append(x)
data_y.append(y)
data_z.append(z)
if len(data_x) > 100:
data_x = data_x[1:]
data_y = data_y[1:]
data_z = data_z[1:]
time_xyz = np.arange(len(data_x))
# print(time_xyz, data_x)
ln_x.set_data(time_xyz, data_x)
ln_y.set_data(time_xyz, data_y)
ln_z.set_data(time_xyz, data_z)
return (ln_x, ln_y, ln_z)
def gen_function():
while True:
(x, y, z) = adxl345.getAxes()
output_string = 'acc '+str(x)+' '+str(y)+' '+str(z)
imu_data_writer.update_data(output_string)
yield (x, y, z)
ani = FuncAnimation(fig, update, frames=gen_function, interval = 100,
init_func=init, blit=True)
plt.show()
Thank you for anyone who can have a look and check out what I have done wrong.
Here is my issue: I have an embedded matplotlib figure in a Qt5 application. When I press the button "edit axis, curve and image parameter", I select my concerned subplot, but only the tab "axis" options appears. it is missing tabs for "curve" and "image".
actual picture
whereas I should have had something like this:
targeted picture
If anyone knows why...
Probably the answer is easy:
If there is no curve (line) in the plot, there will be no "Curves" tab.
If there is no image in the plot, there will be no "Images" tab.
class View2D(MapView):
def show(self, som, what='codebook', which_dim='all', cmap=None,
col_sz=None, desnormalize=False):
(self.width, self.height, indtoshow, no_row_in_plot, no_col_in_plot,
axis_num) = self._calculate_figure_params(som, which_dim, col_sz)
self.prepare()
if not desnormalize:
codebook = som.codebook.matrix
else:
codebook = som._normalizer.denormalize_by(som.data_raw, som.codebook.matrix)
if which_dim == 'all':
names = som._component_names[0]
elif type(which_dim) == int:
names = [som._component_names[0][which_dim]]
elif type(which_dim) == list:
names = som._component_names[0][which_dim]
while axis_num < len(indtoshow):
axis_num += 1
ax = plt.subplot(no_row_in_plot, no_col_in_plot, axis_num)
ind = int(indtoshow[axis_num-1])
min_color_scale = np.mean(codebook[:, ind].flatten()) - 1 * np.std(codebook[:, ind].flatten())
max_color_scale = np.mean(codebook[:, ind].flatten()) + 1 * np.std(codebook[:, ind].flatten())
min_color_scale = min_color_scale if min_color_scale >= min(codebook[:, ind].flatten()) else \
min(codebook[:, ind].flatten())
max_color_scale = max_color_scale if max_color_scale <= max(codebook[:, ind].flatten()) else \
max(codebook[:, ind].flatten())
norm = matplotlib.colors.Normalize(vmin=min_color_scale, vmax=max_color_scale, clip=True)
mp = codebook[:, ind].reshape(som.codebook.mapsize[0],
som.codebook.mapsize[1])
# pl = plt.pcolor(mp[::-1], norm=norm, cmap='jet')
pl = plt.imshow(mp[::-1], interpolation='nearest', origin='lower',cmap='jet')
plt.axis([0, som.codebook.mapsize[1], 0, som.codebook.mapsize[0]])
plt.title(names[axis_num - 1])
ax.set_yticklabels([])
ax.set_xticklabels([])
plt.colorbar(pl)
plt.show()
I'd like to create a barplot in matplotlib:
fig, ax = plt.subplots()
oldbar = ax.bar(x=ind, height=y, width=width)
I'd then like to pickle this barplot to file (either the dictionary or the axes - I'm not sure which is correct):
pickle.dump(oldbar, file('oldbar.pkl', 'w'))
I'd then like to reload this file, and then plot the old bar onto alongside a new bar plot, so I can compare them on a single axes:
fig, ax = plt.subplots()
newbar = ax.bar(x=ind, height=y, width=width)
oldbar = pickle.load(file('oldbar.pkl'))
# I realise the line below doesn't work
ax.bar(oldbar)
plt.show()
Ideally, I'd then like to present them as below. Any suggestions of how I might go about this?
You would pickle the figure instead the artists in it.
import matplotlib.pyplot as plt
import numpy as np
import pickle
ind = np.linspace(1,5,5)
y = np.linspace(9,1,5)
width = 0.3
fig, ax = plt.subplots()
ax.bar(x=ind, height=y, width=width)
ax.set_xlabel("x label")
pickle.dump(fig, file('oldbar.pkl', 'w'))
plt.close("all")
ind2 = np.linspace(1,5,5)
y2 = np.linspace(8,2,5)
width2 = 0.3
fig2 = pickle.load(file('oldbar.pkl'))
ax2 = plt.gca()
ax2.bar(x=ind2+width, height=y2, width=width2, color="C1")
plt.show()
However pickling the data itself may make more sense here.
import matplotlib.pyplot as plt
import numpy as np
import pickle
ind = np.linspace(1,5,5)
y = np.linspace(9,1,5)
width = 0.3
dic = {"ind":ind, "y":y, "width":width}
pickle.dump(dic, file('olddata.pkl', 'w'))
### new data
ind2 = np.linspace(1,5,5)
y2 = np.linspace(8,2,5)
width2 = 0.3
olddic = pickle.load(file('olddata.pkl'))
fig, ax = plt.subplots()
ax.bar(x=olddic["ind"], height=olddic["y"], width=olddic["width"])
ax.bar(x=ind2+olddic["width"], height=y2, width=width2)
ax.set_xlabel("x label")
plt.show()
Maybe this will help:
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
class Data_set(object):
def __init__(self, x=[], y=[], name='data', pklfile=None,
figure=None, axes=None):
"""
"""
if pklfile is None:
self.x = np.asarray(x)
self.y = np.asarray(y)
self.name = str(name)
else:
self.unpickle(pklfile)
self.fig = figure
self.ax = axes
self.bar = None
def plot(self, width=0, offset=0, figure=None, axes=None):
if self.fig is None:
if figure is None:
self.fig = plt.figure()
self.ax = self.fig.subplots(1, 1)
else:
self.fig = figure
if axes is None:
self.ax = self.fig.subplots(1, 1)
else:
self.ax = axes
# maybe there's no need to keep track of self.fig, .ax and .bar,
# but just in case...
if figure is not None:
fig_to_use = figure
if axes is not None:
ax_to_use = axes
else:
ax_to_use = fig_to_use.subplots(1, 1)
else:
fig_to_use = self.fig
ax_to_use = self.ax
if not width:
width = (self.x[1]-self.x[0]) / 2.
self.bar = ax_to_use.bar(x=self.x+offset, height=self.y, width=width)
return fig_to_use, ax_to_use, self.bar
def pickle(self, filename='', ext='.pkl'):
if filename == '':
filename = self.name
with open(filename+ext, 'w') as output_file:
pkl.dump((self.name, self.x, self.y), output_file)
def unpickle(self, filename='', ext='.pkl'):
if filename == '':
filename = self.name
with open(filename + ext, 'r') as input_file:
# the name should really come from the filename, but then the
# above would be confusing?
self.name, self.x, self.y = pkl.load(input_file)
class Data_set_manager(object):
def __init__(self, datasets={}):
self.datasets = datasets
def add_dataset(self, data_set):
self.datasets[data_set.name] = data_set
def add_dataset_from_file(self, filename, ext='.pkl'):
self.datasets[filename] = Data_set(name=filename)
self.datasets[filename].unpickle(filename=filename, ext=ext)
def compare(self, width=0, offset=0, *args):
self.fig = plt.figure()
self.ax = self.fig.subplots(1, 1)
if len(args) == 0:
args = self.datasets.keys()
args.sort()
n = len(args)
if n == 0:
return None, None
if width == 0:
min_dx = None
for dataset in self.datasets.values():
sorted_x = dataset.x.copy()
sorted_x.sort()
try:
new_min_dx = np.min(dataset.x[1:] - dataset.x[:-1])
except ValueError:
# zero-size array to reduction operation minimum which
# has no identity (empty array)
new_min_dx = None
if new_min_dx < min_dx or min_dx is None:
min_dx = new_min_dx
if min_dx is None:
min_dx = 1.
width = float(min_dx) / (n + 1)
offset = float(min_dx) / (n + 1)
offsets = offset*np.arange(n)
if n % 2 == 0:
offsets -= offsets[n/2] - offset/2.
else:
offsets -= offsets[n/2]
i = 0
for name in args:
self.datasets.get(name, Data_set()).plot(width=width,
offset=offsets[i],
figure=self.fig,
axes=self.ax)
i += 1
self.ax.legend(args)
return self.fig, self.ax
if __name__ == "__main__":
# test saving/loading
name = 'test'
to_pickle = Data_set(x=np.arange(10),
y=np.random.rand(10),
name=name)
to_pickle.pickle()
unpickled = Data_set(pklfile=name)
print unpickled.name == to_pickle.name
# test comparison
blorg = Data_set_manager({})
x_step = 1.
n_bars = 4 # also try an odd number
for n in range(n_bars):
blorg.add_dataset(Data_set(x=x_step * np.arange(n_bars),
y=np.random.rand(n_bars),
name='teste' + str(n)))
fig, ax = blorg.compare()
fig.show()
It should work with both even and odd number of bars:
And as long as you keep a record of the names you've used (tip:look in the folder where you are saving them) you can reload the data and compare it with the new one.
More checks could be made (to make sure the file exists, that the x axis is something that can be subtracted before trying to do so, etc.), and it could also use some documentation and proper testing - but this should do in a hurry.
I'm creating a interactive chart with the seaborn package.
It's a simple chart with dates on the x axis and value from 0 to 5 on the y axis
I can move a cursor-bar over it left and right, with arrow keys and set the y value of the chart with num keys (and export to csv the charts y values with their timestamp).
However when large date ranges are used the program becomes incredibly slow.
I press the arrow keys to move the cursor one bar but it can take one or 2 seconds to react. (the key control are done with PyQT)
Any idea what i might do to speed it up?
Please feel free to copy paste the code and run it in python to see the program:
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
from datetime import timedelta, date
import numpy as np
matplotlib.use('Qt4Agg')
import seaborn as sns
from matplotlib.widgets import Button
import matplotlib.lines
from matplotlib.lines import Line2D
import csv
from itertools import izip
dates = []
values = []
sns.set(style="ticks")
fig = plt.figure(1, figsize=(25,7))
fig.clf()
ax = fig.add_subplot(111)
fig.canvas.draw()
plt.ylim(0,5)
horizontal_position = 0
periods = 365
idx = pd.DatetimeIndex(start='2010-01-01', freq='d', periods=periods)
index_delete = []
for i in range(idx.size):
if idx[i].dayofweek == 6 or idx[i].dayofweek == 5:
index_delete.append(i)
idx = idx.delete(index_delete)
periods = idx.size
idx_x_array = np.array(range(idx.size), dtype=np.int32)
str_vals = []
first_day_lines = []
counter = 0
if periods > 170:
for s in idx._data:
s = str(s)
day = s[8:10]
month = s[5:7]
year = s[0:4]
if day == '01':
dotted_line_f = plt.Line2D((counter, counter), (0, 5), lw=2., marker='.',
color='gray')
first_day_lines.append(dotted_line_f)
date_str = day+'/'+month+'/'+year
str_vals.append(date_str)
elif idx.dayofweek[counter]:
date_str = day+'/'+month
str_vals.append(date_str)
else:
str_vals.append('')
counter +=1
if periods <= 170:
for s in idx._data:
s = str(s)
day = s[8:10]
month = s[5:7]
year = s[0:4]
if day == '01':
dotted_line_f = plt.Line2D((counter, counter), (0, 5), lw=2., marker='.',
color='gray')
first_day_lines.append(dotted_line_f)
date_str = day+'/'+month+'/'+year
str_vals.append(date_str)
else:
date_str = day+'/'+month
str_vals.append(date_str)
counter +=1
plt.grid(True)
plt.xticks(idx_x_array, str_vals, rotation='vertical', fontsize=7)
values = []
for i in idx_x_array:
values.append(0)
data= pd.DataFrame({('A','a'):values}, idx)
sns.set_context(context={"figure.figsize":(5,5)})
ab = sns.tsplot(data.T.values, idx_x_array)
ab.lines[0].set_color('red')
# x_len = len(ab.lines[0]._x)
ab.lines[0]._x = idx_x_array
dotted_line = plt.Line2D((1, 1), (0, 5), lw=2.,
ls='-.', marker='.',
markersize=1,
color='black',
markerfacecolor='black',
markeredgecolor='black',
alpha=0.5)
ab.add_line(dotted_line)
for line in first_day_lines:
ab.add_line(line)
lines = ab.lines
init_focus = ab.lines[0]
index_focus = 0
bbox_props = dict(boxstyle="rarrow,pad=0.3", fc="pink", ec="b", lw=2)
horizontal_position = init_focus._x[index_focus]
plt.subplots_adjust(bottom=.30, left=.03, right=.97, top=.90, hspace=.35)
analysis_label = 'Analysis mode'
discovery_label = 'Discovery mode'
def chart_mode(event):
global button_label
global dotted_line
global power
global horizontal_position
global index_focus
global dotted_line
global idx
if button_label == analysis_label:
index_focus = 0
button_label = discovery_label
plt.draw()
elif button_label == discovery_label:
index_focus = periods-1
button_label = analysis_label
plt.draw()
bnext.label.set_text(button_label)
horizontal_position = ab.lines[0]._x[index_focus]
dotted_line = plt.Line2D((horizontal_position,horizontal_position), (0, 5), lw=5.,
ls='-.', marker='.',
markersize=1,
color='black',
markerfacecolor='black',
markeredgecolor='black',
alpha=0.5)
ax.add_line(dotted_line)
new_line = ax.lines.pop()
ax.lines[1] = new_line
def export_csv(event):
x_data = idx._data
y_data = ab.lines[0]._y
x_data_proc = []
for x in x_data:
x = str(x)
day = x[8:10]
month = x[5:7]
year = x[0:4]
date_str = day+'/'+month
x_data_proc.append(date_str)
y_data_proc = []
for y in y_data:
y_data_proc.append(int(y))
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(izip(x_data_proc, y_data_proc))
button_label = analysis_label
axnext = plt.axes([0.1, 0.05, 0.1, 0.075])
bnext = Button(axnext, button_label)
bnext.on_clicked(chart_mode)
axexport = plt.axes([0.21, 0.05, 0.1, 0.075])
bexport = Button(axexport, 'export csv')
bexport.on_clicked(export_csv)
def on_keyboard(event):
global power
global horizontal_position
global index_focus
global dotted_line
global idx
if event.key == 'right':
if index_focus < periods-1:
index_focus+=1
else:
idx = idx + timedelta(days=1)
index_focus+=1
elif event.key == 'left':
if index_focus > 0:
index_focus-=1
elif event.key == 'up':
if index_focus < periods-5:
index_focus+=5
elif event.key == 'down':
if index_focus > 5:
index_focus-=5
elif is_number(event.key):
for i in range(len(ab.lines[0]._y[index_focus::])):
ab.lines[0]._y[index_focus+i] = event.key
horizontal_position = ab.lines[0]._x[index_focus]
dotted_line = plt.Line2D((horizontal_position,horizontal_position), (0, 5), lw=2.,
ls='-.', marker='.',
markersize=1,
color='black',
markerfacecolor='black',
markeredgecolor='black',
alpha=0.5)
ax.add_line(dotted_line)
new_line = ax.lines.pop()
ax.lines[1] = new_line
fig.canvas.draw()
plt.show()
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
plt.gcf().canvas.mpl_connect('key_press_event', on_keyboard)
plt.show()
I'm afraid this code is too long for me to plough through.
Nonetheless, a couple of easy ways to help find bottlenecks:
interrupt the slow program, and look at the stack trace; repeat 5 times.
In your case these will have lots of incomprehensible calls in Qt4 etc.,
but you might be able to see what your code is calling that's slow.
good old print: add e.g. print "%.3f %s" % (time.time() - t0, event.key) in on_keyboard .
Then, comment out the drawing stuff, print only, run blind: is the time spent in drawing,
or somewhere else ?
Also, why Qt4Agg -- is TkAgg just as slow ?
Also, what does "when large date ranges are used" mean -- how large ?