How can I move xticks and xticklabels up? - python

I've got this code that is supposed to make a heatmap, but with circles instead of squares/rectangles, so far testing it with placeholder colors, looks like this:
import matplotlib.pyplot as plt
import matplotlib.colors as mcl
import numpy as np
import pandas as pd
from typing import List, T
from random import uniform
def l_flatten(l: List[T]) -> List[T]:
return [j for i in l for j in i]
def get_luminance(color: str) -> float:
# taken from Seaborn's utils
rgb = mcl.colorConverter.to_rgba_array(color)[:, :3]
rgb = np.where(rgb <= .03928, rgb / 12.92, ((rgb + .055) / 1.055) ** 2.4)
lum = rgb.dot([.2126, .7152, .0722])
try:
lum = lum.item()
except ValueError:
pass
return lum
class CircleHeatmap:
def __init__(self,
ax: plt.Axes,
df: pd.DataFrame,
colors: List[str],
annot_show: bool,
annot_size: float,
circle_size: float,
x_labels: List[str],
x_labels_size: float,
x_labels_color: str,
y_labels: List[str],
y_labels_size: float,
y_labels_color: str) -> None:
# pass user-provided variables
self.ax = ax
self.df = df
self.colors = colors
self.annot_show = annot_show
self.annot_size = annot_size
self.circle_size = circle_size
self.x_labels = x_labels
self.x_labels_size = x_labels_size
self.x_labels_color = x_labels_color
self.y_labels = y_labels
self.y_labels_size = y_labels_size
self.y_labels_color = y_labels_color
# pass technical variables
self.y_size, self.x_size = self.df.shape
self.x_arr, self.y_arr = np.meshgrid(np.arange(self.x_size),
np.arange(self.y_size))
self.x_arr, self.y_arr = ((self.x_arr + 0.5).flat,
(self.y_arr + 0.5).flat)
self.x_len, self.y_len = [np.linspace(0, len(i), len(i) + 1)[:-1] + 0.5
for i in (self.x_labels, self.y_labels)]
self.df_values = l_flatten(self.df.values.tolist())
def plot(self) -> None:
self.ax.scatter(self.x_arr, self.y_arr,
s = self.circle_size ** 2,
c = self.colors)
def labels(self) -> None:
self.ax.set_xticks(self.x_len)
self.ax.set_yticks(self.y_len)
self.ax.set_xticklabels(self.x_labels, fontsize = self.x_labels_size,
color = self.x_labels_color)
self.ax.set_yticklabels(self.y_labels, fontsize = self.y_labels_size,
color = self.y_labels_color)
def main() -> None:
fig, ax = plt.subplots(figsize = (20, 30))
df = pd.DataFrame([[uniform(0, 1) for j in range(20)] for i in range(30)])
colors = ["#EC4E20", "#FF9505", "#016FB9"] * 200
heatmap = CircleHeatmap(ax = ax,
df = df,
colors = colors,
annot_show = False,
annot_size = 16,
circle_size = 45,
x_labels = [i for i in range(20)],
x_labels_size = 20,
x_labels_color = "black",
y_labels = [i for i in range(30)],
y_labels_size = 20,
y_labels_color = "black")
heatmap.plot()
heatmap.labels()
for i in ["top", "bottom", "right", "left"]:
ax.spines[i].set_visible(False)
plt.savefig("test2.png")
if __name__ == "__main__":
main()
As a result, I get something like this. My question is: how can I move the ticks and the labels on the x-axis up a little bit, preferrably with an option to control them with a variable?

I had a similar result, but only commented on the settings since you were so familiar with them. Once again, a fix was needed and I will respond with the corrected code. I don't know if I was able to add the code in the best place. The following code can help.
def labels(self) -> None:
self.ax.set_xticks(self.x_len)
self.ax.set_yticks(self.y_len)
self.ax.spines['bottom'].set_position(('data', 0))
self.ax.spines['left'].set_position(('data', 0))
self.ax.set_xticklabels(self.x_labels, fontsize = self.x_labels_size,
color = self.x_labels_color)
self.ax.set_yticklabels(self.y_labels, fontsize = self.y_labels_size,
color = self.y_labels_color)

Related

PYTHON: how can I add a linear regression to this bokeh?

how can I add a linar regression to this bokeh?, I have trouble with this, and dont know how to add to the figure the lr (don't know how to add to the curdoc expression). I've seen other posts, but havent found the way to add it to the bokeh. Please, help me with this showing how to add that line to the figure.
import pandas as pd
from bokeh.layouts import column, row
from bokeh.models import Select
from bokeh.palettes import Spectral5
from bokeh.plotting import curdoc, figure
from bokeh.sampledata.autompg import autompg_clean as df
df = df.copy()
SIZES = list(range(6, 22, 3))
COLORS = Spectral5
N_SIZES = len(SIZES)
N_COLORS = len(COLORS)
# data cleanup
df.cyl = df.cyl.astype(str)
df.yr = df.yr.astype(str)
del df['name']
columns = sorted(df.columns)
discrete = [x for x in columns if df[x].dtype == object]
continuous = [x for x in columns if x not in discrete]
def create_figure():
xs = df[x.value].values
ys = df[y.value].values
x_title = x.value.title()
y_title = y.value.title()
kw = dict()
if x.value in discrete:
kw['x_range'] = sorted(set(xs))
if y.value in discrete:
kw['y_range'] = sorted(set(ys))
kw['title'] = "%s vs %s" % (x_title, y_title)
p = figure(height=600, width=800, tools='pan,box_zoom,hover,reset', **kw)
p.xaxis.axis_label = x_title
p.yaxis.axis_label = y_title
if x.value in discrete:
p.xaxis.major_label_orientation = pd.np.pi / 4
sz = 9
if size.value != 'None':
if len(set(df[size.value])) > N_SIZES:
groups = pd.qcut(df[size.value].values, N_SIZES, duplicates='drop')
else:
groups = pd.Categorical(df[size.value])
sz = [SIZES[xx] for xx in groups.codes]
c = "#31AADE"
if color.value != 'None':
if len(set(df[color.value])) > N_COLORS:
groups = pd.qcut(df[color.value].values, N_COLORS, duplicates='drop')
else:
groups = pd.Categorical(df[color.value])
c = [COLORS[xx] for xx in groups.codes]
p.circle(x=xs, y=ys, color=c, size=sz, line_color="white", alpha=0.6, hover_color='white', hover_alpha=0.5)
return p
def update(attr, old, new):
layout.children[1] = create_figure()
x = Select(title='X-Axis', value='mpg', options=columns)
x.on_change('value', update)
y = Select(title='Y-Axis', value='hp', options=columns)
y.on_change('value', update)
size = Select(title='Size', value='None', options=['None'] + continuous)
size.on_change('value', update)
color = Select(title='Color', value='None', options=['None'] + continuous)
color.on_change('value', update)
controls = column(x, y, color, size, width=200)
layout = row(controls, create_figure())
curdoc().add_root(layout)
curdoc().title = "Crossfilter"

Using Floatslider for matplotlib.pyplot

I am coding two different graphs where they are supposed to be alike when a constant dt is a correct value. A part of the assignment is to make a widget slider that controls the constant dt, so when you run the code, the slider appears on the plot and lets you control the constant and changing the graph. However when I run this code:
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, FloatSlider
#constants
T0 = 83 #[celcius]
Ts = 22.8 #[celcius]
r = 0.1 #[min-1]
#The analytical solution. Part i:
def T(t):
return Ts + (T0 - Ts)*np.exp(-r*t)
t50 = np.arange(0, 50.1, 0.1)
Tanalytisk = []
for i in range(len(t50)):
Tanalytisk.append(T(t50[i]))
#Numerical solution. Part ii:
tslutt = 50
h = 1
def f(T):
return -r*(T-Ts)
def euler(f):
Tn = [T0]
tn = [0]
while(tn[-1] < tslutt):
t, y = tn[-1], Tn[-1]
Tn.append(y + h*f(y))
tn.append(t + h)
return (np.array(tn), np.array(Tn))
tn, Tn = euler(f)
plt.plot(t50, Tanalytisk,label="Analytical") #Analytical solution
plt.plot(tn, Tn, label = "Numerical") #Numerical solution
plt.plot(time, temp, label = "Experimental")
plt.xlabel("Time [min]")
plt.ylabel("Temperature [C]")
plt.title("Analytical solution T(t)")
plt.legend()
plt.show()
håndtak = FloatSlider(value = 1, min = 0, max = 15, step = 0.1, description = "dt")
interact(euler(f), h = håndtak)
I end up with this error:
> TypeError Traceback (most recent call last)
~\anaconda3\lib\site-packages\ipywidgets\widgets\interaction.py in update(self, *args)
254 value = widget.get_interact_value()
255 self.kwargs[widget._kwarg] = value
--> 256 self.result = self.f(**self.kwargs)
257 show_inline_matplotlib_plots()
258 if self.auto_display and self.result is not None:
TypeError: 'tuple' object is not callable
<function ipywidgets.widgets.interaction._InteractFactory.__call__.<locals>.<lambda>(*args,
**kwargs)>
How do I understand the problem and how can I make the widget work? It appears on the graph but doesn't change the graph when changing the value.
Is there an easier way to code the slider?
Thanks in advance!
You haven't define time and temp variables so I commented them. Anyway here's how you put the slider in your code :
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as wg
#wg.interact(h = wg.FloatSlider(min = 0, max = 15, step = 0.1, value=1, description = "dt"))
def run(h):
#constants
T0 = 83 #[celcius]
Ts = 22.8 #[celcius]
r = 0.1 #[min-1]
#The analytical solution. Part i:
def T(t):
return Ts + (T0 - Ts)*np.exp(-r*t)
t50 = np.arange(0, 50.1, 0.1)
Tanalytisk = []
for i in range(len(t50)):
Tanalytisk.append(T(t50[i]))
#Numerical solution. Part ii:
tslutt = 50
# h = 1
def f(T):
return -r*(T-Ts)
def euler(f,h):
Tn = [T0]
tn = [0]
while(tn[-1] < tslutt):
t, y = tn[-1], Tn[-1]
Tn.append(y + h*f(y))
tn.append(t + h)
return (np.array(tn), np.array(Tn))
tn, Tn = euler(f,h)
plt.plot(t50, Tanalytisk,label="Analytical") #Analytical solution
plt.plot(tn, Tn, label = "Numerical") #Numerical solution
# plt.plot(time, temp, label = "Experimental")
plt.xlabel("Time [min]")
plt.ylabel("Temperature [C]")
plt.title("Analytical solution T(t)")
plt.legend();

matplotlib subplots very slow

The following code
from torch.utils.data import DataLoader
from defect_segmentation.data_loading.DatasetSingleImage import dataset_single_image_default
import numpy as np
if __name__ == "__main__":
import matplotlib.pyplot as plt
def main():
dataset = dataset_single_image_default()
batch_size = 16
shuffle = True
num_workers = 0
loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers)
for i_batch, sample_batched in enumerate(loader):
fig, axs = plt.subplots(int(np.sqrt(batch_size)), batch_size // int(np.sqrt(batch_size)))
fig.suptitle(f"i_batch = {i_batch}")
for i_sample, ax in zip(range(sample_batched.shape[0]), axs.flat):
ax.set_title(f"Sample #{i_sample}")
ax.axis("off")
ax.imshow(sample_batched[i_sample, :, :])
plt.pause(0.001)
main()
works and outputs figures like so
This is fine.
Problem is by the 10th figure, it becomes very slow to populate the figures. I don't know what can be causing this.
For completeness, here is the code for creating the dataset (striding over a single image):
from torch.utils.data import Dataset
from Utils.ConfigProvider import ConfigProvider
import cv2
import os
from overrides import overrides # pip install overrides
class DatasetSingleImage(Dataset):
def __init__(self, image_path: str, sample_shape: tuple, strides: tuple):
self._path = image_path
assert os.path.isfile(self._path)
self._im = cv2.imread(self._path)
self._shape = self._im.shape
self._rows, self._cols = self._shape[0], self._shape[1]
self._sample_shape = sample_shape
self._sample_rows, self._sample_cols = self._sample_shape[0], self._sample_shape[1]
self._strides = strides
self._stride_rows, self._stride_cols = self._strides[0], self._strides[1]
# self._rows_start_range = range(0, self._rows, self._stride_rows)
# self._cols_start_range = range(0, self._cols, self._stride_cols)
self._rows_tuples_range = \
[(c, min(c + self._sample_rows, self._rows)) for c in range(0, self._rows - self._sample_rows, self._stride_rows)]
self._cols_tuples_range = \
[(r, min(r + self._sample_cols, self._cols)) for r in range(0, self._cols - self._sample_cols, self._stride_cols)]
self._n_strides_rows = len(self._rows_tuples_range)
self._n_strides_cols = len(self._cols_tuples_range)
self._total_strides = self._n_strides_rows * self._n_strides_cols
def __len__(self):
return self._total_strides
#overrides # pip install overrides
def __getitem__(self, ind):
row_ind = ind // self._n_strides_cols
col_ind = ind % self._n_strides_cols
sample_x = self._rows_tuples_range[row_ind]
sample_y = self._cols_tuples_range[col_ind]
sample = self._im[sample_x[0]:sample_x[1], sample_y[0]:sample_y[1]]
assert sample.shape[:2] == self._sample_shape
return sample
def dataset_single_image_default():
path = ConfigProvider.config().data.defective_inspected_path1
sample_shape = (50, 50)
strides = (25, 25)
dataset = DatasetSingleImage(path, sample_shape, strides)
return dataset
What is making the plotting slow, and how to fix it?

Filling shapefile polygons partially in basemap

I would like to fill a polygon using basemap/shapefile data, but only a certain %. For example, in the example below, we fill based on the values, but let's say I wanted to fill a % of the polygon based on these values (code from here):
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
import numpy as np
fig= plt.figure()
ax= fig.add_subplot(111)
m=Basemap(projection='cyl',llcrnrlat=34.5,llcrnrlon=19,
urcrnrlat=42,urcrnrlon=28.5,resolution='h')
m.drawmapboundary(fill_color='aqua')
m.fillcontinents(color='w',lake_color='aqua')
m.drawcoastlines()
m.readshapefile('data/nomoi/nomoi','nomoi')
dict1={14464: 1.16, 14465: 1.35, 14466: 1.28, 14467: 1.69, 14468: 1.81, 14418: 1.38}
colvals = dict1.values()
cmap=plt.cm.RdYlBu
norm=plt.Normalize(min(colvals),max(colvals))
patches = []
for info, shape in zip(m.nomoi_info, m.nomoi):
if info['ID_2'] in list(dict1.keys()):
color=cmap(norm(dict1[info['ID_2']]))
patches.append( Polygon(np.array(shape), True, color=color) )
pc = PatchCollection(patches, match_original=True, edgecolor='k', linewidths=1., zorder=2)
ax.add_collection(pc)
#colorbar
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array(colvals)
fig.colorbar(sm, ax=ax)
plt.show()
Thank you.
import math
from shapely.geometry import Polygon as shpoly
#shapefile of main massachusetts shape
iowpoly = state_shapes['Massachusetts'][32]
def return_xy(coords):
return [np.asarray([i[0] for i in coords]), np.asarray([i[1] for i in coords])]
def return_area(coords):
x, y = return_xy(coords)
return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))
def return_bounding_box(coords):
x, y = return_xy(coords)
return [[min(x), min(y)], [max(x), max(y)]]
def split_x_wise(bbox, weights, split = 2):
lleft = bbox[0]
uright = bbox[1]
dx = abs(uright[0] - lleft[0])
weights = np.cumsum(sorted(weights, reverse=True))
xcoords = [lleft[0]+weights[x-1]*dx for x in range(1, split)]
return xcoords
def generate_splits_by_area(coords, bbox, weights, tolerance = 0.03, div = 100):
xareasplits = {}
weights = np.cumsum(sorted(weights, reverse=True))[:-1]
lleft = bbox[0]
uright = bbox[1]
dx = abs(uright[0] - lleft[0])
xsplit = [lleft[0]+(dx/div)*x for x in range(1, div)]
for w in weights:
xareasplits[str(w)] = None
mainarea = shpoly(coords).area
for i, s in enumerate(xsplit):
poly = []
if i == 0:
continue
for ip, p in enumerate(coords):
if p[0] < s:
poly.append(p)
shpl = shpoly(poly).area
frac = shpl/mainarea
for w in weights:
if abs(w-frac) <= tolerance:
if xareasplits[str(w)] == None:
xareasplits[str(w)] = s
return list(xareasplits.values())
def return_split(coords, weights, split = 2, by_area = False, tolerance = 0.03, div = 100):
polys = {}
for x in range(0, split):
polys[str(x+1)] = {'points':[], 'maxit' : None}
bbox = return_bounding_box(coords)
if not by_area:
xsplit = split_x_wise(bbox, weights, split)
#test = generate_splits_by_area(coords, bbox, weights, tolerance=tolerance, div=div)
else:
xsplit = generate_splits_by_area(coords, bbox, weights, tolerance=tolerance, div=div)
xsplit.append(bbox[0][0])
xsplit.append(bbox[1][0])
xsplit = sorted(xsplit)
#print(xsplit)
#print(test)
for ip, p in enumerate(coords):
for i, splt in enumerate(xsplit):
if i > 0:
if (p[0] > xsplit[i-1]) & (p[0] < splt):
if len(polys[str(i)]['points']) == 0:
polys[str(i)]['points'].append(coords[ip-1])
polys[str(i)]['points'].append(p)
polys[str(i)]['maxit'] = ip
for poly, data in polys.items():
tmaxit = data['maxit']+1
if tmaxit >= len(coords):
data['points'].append(coords[0])
else:
data['points'].append(coords[tmaxit])
return polys
#return [p for p in coords if p[0] > xsplit[0]]
#bboxiowa = return_bounding_box(iowpoly)
splitpoly = return_split(iowpoly, weights = [0.2780539772727273, 0.1953716856060606, 0.19513494318181818, 0.18329782196969696, 0.14814157196969696],by_area = True,split = 5)
for k, v in splitpoly.items():
print (k, len(v['points']))
print (v['maxit'])
test = shpoly(splitpoly["1"]['points'])
test
I managed to write my own code to split and fill shapel polygons from shapefiles. The above code example splits the Massachusetts shapefile into 5 segments, weighted according to weights and by area.
The first 2 parts of the split look like this:

Very slow plot with Matlpotlib

Can anybody help how to optimize the plot function in python? I use Matplotlib to plot financial data.Here small function for plotting OHLC data. The time increase significantly if I add indicators or other data.
import numpy as np
import datetime
from matplotlib.collections import LineCollection
from pylab import *
import urllib2
def test_plot(OHLCV):
bar_width = 1.3
date_offset = 0.5
fig = figure(figsize=(50, 20), facecolor='w')
ax = fig.add_subplot(1, 1, 1)
labels = ax.get_xmajorticklabels()
setp(labels, rotation=0)
month = MonthLocator()
day = DayLocator()
timeFmt = DateFormatter('%Y-%m-%d')
colormap = OHLCV[:,1] < OHLCV[:,4]
color = np.zeros(colormap.__len__(), dtype = np.dtype('|S5'))
color[:] = 'red'
color[np.where(colormap)] = 'green'
dates = date2num( OHLCV[:,0])
lines_hl = LineCollection( zip(zip(dates, OHLCV[:,2]), zip(dates, OHLCV[:,3])))
lines_hl.set_color(color)
lines_hl.set_linewidth(bar_width)
lines_op = LineCollection( zip(zip((np.array(dates) - date_offset).tolist(), OHLCV[:,1]), zip((np.array(dates)).tolist(), parsed_table[:,1])))
lines_op.set_color(color)
lines_op.set_linewidth(bar_width)
lines_cl = LineCollection( zip(zip((np.array(dates) + date_offset).tolist(), OHLCV[:,4]), zip((np.array(dates)).tolist(), parsed_table[:,4])))
lines_cl.set_color(color)
lines_cl.set_linewidth(bar_width)
ax.add_collection(lines_hl, autolim=True)
ax.add_collection(lines_cl, autolim=True)
ax.add_collection(lines_op, autolim=True)
ax.xaxis.set_major_locator(month)
ax.xaxis.set_major_formatter(timeFmt)
ax.xaxis.set_minor_locator(day)
ax.autoscale_view()
ax.xaxis.grid(True, 'major')
ax.grid(True)
ax.set_title('EOD test plot')
ax.set_xlabel('Date')
ax.set_ylabel('Price , $')
fig.savefig('test.png', dpi = 50, bbox_inches='tight')
close()
if __name__=='__main__':
data_table = urllib2.urlopen(r"http://ichart.finance.yahoo.com/table.csv?s=IBM&a=00&b=1&c=2012&d=00&e=15&f=2013&g=d&ignore=.csv").readlines()[1:][::-1]
parsed_table = []
#Format: Date, Open, High, Low, Close, Volume
dtype = (lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').date(),float, float, float, float, int)
for row in data_table:
field = row.strip().split(',')[:-1]
data_tmp = [i(j) for i,j in zip(dtype, field)]
parsed_table.append(data_tmp)
parsed_table = np.array(parsed_table)
import time
bf = time.time()
count = 100
for i in xrange(count):
test_plot(parsed_table)
print('Plot time: %s' %(time.time() - bf) / count)
The result is something like this. Average time execution on each plot is aproximately 2.6s. Charting in R is much faster, but I didn't measure the performance and I don't want use Rpy, so I bielive that my code is inefficient.
This solution reuses a Figure instance and saves plots asynchronously. You could change this to have as many figures as there are processors, do that many plots asynchronously, and it should speed things up even more. As it is, this takes ~1s per plot, down from 2.6 on my machine.
import numpy as np
import datetime
import urllib2
import time
import multiprocessing as mp
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pylab import *
from matplotlib.collections import LineCollection
class AsyncPlotter():
def __init__(self, processes=mp.cpu_count()):
self.manager = mp.Manager()
self.nc = self.manager.Value('i', 0)
self.pids = []
self.processes = processes
def async_plotter(self, nc, fig, filename, processes):
while nc.value >= processes:
time.sleep(0.1)
nc.value += 1
print "Plotting " + filename
fig.savefig(filename)
plt.close(fig)
nc.value -= 1
def save(self, fig, filename):
p = mp.Process(target=self.async_plotter,
args=(self.nc, fig, filename, self.processes))
p.start()
self.pids.append(p)
def join(self):
for p in self.pids:
p.join()
class FinanceChart():
def __init__(self, async_plotter):
self.async_plotter = async_plotter
self.bar_width = 1.3
self.date_offset = 0.5
self.fig = plt.figure(figsize=(50, 20), facecolor='w')
self.ax = self.fig.add_subplot(1, 1, 1)
self.labels = self.ax.get_xmajorticklabels()
setp(self.labels, rotation=0)
line_hl = LineCollection(([[(734881,1), (734882,5), (734883,9), (734889,5)]]))
line_op = LineCollection(([[(734881,1), (734882,5), (734883,9), (734889,5)]]))
line_cl = LineCollection(([[(734881,1), (734882,5), (734883,9), (734889,5)]]))
self.lines_hl = self.ax.add_collection(line_hl, autolim=True)
self.lines_op = self.ax.add_collection(line_cl, autolim=True)
self.lines_cl = self.ax.add_collection(line_op, autolim=True)
self.ax.set_title('EOD test plot')
self.ax.set_xlabel('Date')
self.ax.set_ylabel('Price , $')
month = MonthLocator()
day = DayLocator()
timeFmt = DateFormatter('%Y-%m-%d')
self.ax.xaxis.set_major_locator(month)
self.ax.xaxis.set_major_formatter(timeFmt)
self.ax.xaxis.set_minor_locator(day)
def test_plot(self, OHLCV, i):
colormap = OHLCV[:,1] < OHLCV[:,4]
color = np.zeros(colormap.__len__(), dtype = np.dtype('|S5'))
color[:] = 'red'
color[np.where(colormap)] = 'green'
dates = date2num( OHLCV[:,0])
date_array = np.array(dates)
xmin = min(dates)
xmax = max(dates)
ymin = min(OHLCV[:,1])
ymax = max(OHLCV[:,1])
self.lines_hl.set_segments( zip(zip(dates, OHLCV[:,2]), zip(dates, OHLCV[:,3])))
self.lines_hl.set_color(color)
self.lines_hl.set_linewidth(self.bar_width)
self.lines_op.set_segments( zip(zip((date_array - self.date_offset).tolist(), OHLCV[:,1]), zip(date_array.tolist(), OHLCV[:,1])))
self.lines_op.set_color(color)
self.lines_op.set_linewidth(self.bar_width)
self.lines_cl.set_segments( zip(zip((date_array + self.date_offset).tolist(), OHLCV[:,4]), zip(date_array.tolist(), OHLCV[:,4])))
self.lines_cl.set_color(color)
self.lines_cl.set_linewidth(self.bar_width)
self.ax.set_xlim(xmin,xmax)
self.ax.set_ylim(ymin,ymax)
self.ax.xaxis.grid(True, 'major')
self.ax.grid(True)
self.async_plotter.save(self.fig, '%04i.png'%i)
if __name__=='__main__':
print "Starting"
data_table = urllib2.urlopen(r"http://ichart.finance.yahoo.com/table.csv?s=IBM&a=00&b=1&c=2012&d=00&e=15&f=2013&g=d&ignore=.csv").readlines()[1:][::-1]
parsed_table = []
#Format: Date, Open, High, Low, Close, Volume
dtype = (lambda x: datetime.datetime.strptime(x, '%Y-%m-%d').date(),float, float, float, float, int)
for row in data_table:
field = row.strip().split(',')[:-1]
data_tmp = [i(j) for i,j in zip(dtype, field)]
parsed_table.append(data_tmp)
parsed_table = np.array(parsed_table)
import time
bf = time.time()
count = 10
a = AsyncPlotter()
_chart = FinanceChart(a)
print "Done with startup tasks"
for i in xrange(count):
_chart.test_plot(parsed_table, i)
a.join()
print('Plot time: %.2f' %(float(time.time() - bf) / float(count)))

Categories

Resources