def _ticker(self): ''' Return two sequences: ticks (colorbar data locations) and ticklabels (strings). ''' locator = self.locator formatter = self.formatter if locator is None: if self.boundaries is None: if isinstance(self.norm, colors.no_norm): nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=0) else: locator = ticker.MaxNLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.no_norm): intv = Interval(Value(self._values[0]), Value(self._values[-1])) else: intv = Interval(Value(self.vmin), Value(self.vmax)) locator.set_view_interval(intv) locator.set_data_interval(intv) formatter.set_view_interval(intv) formatter.set_data_interval(intv) b = nx.array(locator()) eps = 0.001 * (self.vmax - self.vmin) b = nx.compress((b >= self.vmin - eps) & (b <= self.vmax + eps), b) ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t) for t in b] offset_string = formatter.get_offset() return ticks, ticklabels, offset_string
def index_bar( ax, vals, facecolor='b', edgecolor='l', width=4, alpha=1.0, ): """ Add a bar collection graph with height vals (-1 is missing). ax : an Axes instance to plot to width : the bar width in points alpha : bar transparency """ facecolors = (colorConverter.to_rgba(facecolor, alpha), ) edgecolors = (colorConverter.to_rgba(edgecolor, alpha), ) right = width / 2.0 left = -width / 2.0 bars = [((left, 0), (left, v), (right, v), (right, 0)) for v in vals if v != -1] sx = ax.figure.dpi * Value(1 / 72.0) # scale for points sy = (ax.bbox.ur().y() - ax.bbox.ll().y()) / (ax.viewLim.ur().y() - ax.viewLim.ll().y()) barTransform = scale_sep_transform(sx, sy) offsetsBars = [(i, 0) for i, v in enumerate(vals) if v != -1] barCollection = PolyCollection( bars, facecolors=facecolors, edgecolors=edgecolors, antialiaseds=(0, ), linewidths=(0.5, ), offsets=offsetsBars, transOffset=ax.transData, ) barCollection.set_transform(barTransform) minx, maxx = (0, len(offsetsBars)) miny = 0 maxy = max([v for v in vals if v != -1]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(barCollection) return barCollection
def write_header(self): from matplotlib.backends.backend_agg import RendererAgg try: from matplotlib.transforms import Value except ImportError: dpi = 72 else: dpi = Value(72) self.renderer = RendererAgg(self.w, self.h, dpi)
def render_figure_as_image(self, wFig, hFig, dpi): """ Renders a matplotlib figure using the Agg backend and stores the result in a C{wx.Image}. The arguments C{wFig} and {hFig} are the width and height of the figure, and C{dpi} is the dots-per-inch to render at. """ figure = self.figure if mat_ver < zoom_ver: old_dpi = figure.dpi.get() figure.dpi.set(dpi) old_width = figure.figwidth.get() figure.figwidth.set(wFig) old_height = figure.figheight.get() figure.figheight.set(hFig) wFig_Px = int(figure.bbox.width()) hFig_Px = int(figure.bbox.height()) agg = RendererAgg(wFig_Px, hFig_Px, Value(dpi)) else: old_dpi = figure.get_dpi() figure.set_dpi(dpi) old_width = figure.get_figwidth() figure.set_figwidth(wFig) old_height = figure.get_figheight() figure.set_figheight(hFig) old_frameon = figure.frameon figure.frameon = False wFig_Px = int(figure.bbox.width) hFig_Px = int(figure.bbox.height) agg = RendererAgg(wFig_Px, hFig_Px, dpi) figure.draw(agg) if mat_ver < zoom_ver: figure.dpi.set(old_dpi) figure.figwidth.set(old_width) figure.figheight.set(old_height) else: figure.set_dpi(old_dpi) figure.set_figwidth(old_width) figure.set_figheight(old_height) figure.frameon = old_frameon image = wx.EmptyImage(wFig_Px, hFig_Px) image.SetData(agg.tostring_rgb()) return image
def write_header(self, resolution=72): from matplotlib.backends.backend_agg import RendererAgg, Figure from matplotlib.backend_bases import GraphicsContextBase try: from matplotlib.transforms import Value except ImportError: dpi = resolution else: dpi = Value(resolution) self.renderer = RendererAgg(self.w, self.h, dpi) self.figure = Figure() self.gc = GraphicsContextBase() self.gc.set_linewidth(.2)
def rand_point(): xy = rand(2) return Point(Value(xy[0]), Value(xy[1]))
def closeto_seq(xs, ys): return alltrue([closeto(x, y) for x, y in zip(xs, ys)]) def closeto_bbox(b1, b2): xmin1, xmax1 = b1.intervalx().get_bounds() ymin1, ymax1 = b1.intervaly().get_bounds() xmin2, xmax2 = b2.intervalx().get_bounds() ymin2, ymax2 = b2.intervaly().get_bounds() pairs = ((xmin1, xmin2), (xmax1, xmax2), (ymin1, ymin2), (ymax1, ymax2)) return alltrue([closeto(x, y) for x, y in pairs]) ll = Point(Value(10), Value(10)) ur = Point(Value(200), Value(40)) bbox = Bbox(ll, ur) assert (bbox.xmin() == 10) assert (bbox.width() == 190) assert (bbox.height() == 30) ll.x().set(12.0) assert (bbox.xmin() == 12) assert (bbox.width() == 188) assert (bbox.height() == 30) a = Value(10) b = Value(0)
def volume_overlay3(ax, quotes, colorup='k', colordown='r', width=4, alpha=1.0): """ Add a volume overlay to the current axes. quotes is a list of (d, open, close, high, low, volume) and close-open is used to determine the color of the bar kwarg width : the bar width in points colorup : the color of the lines where close1 >= close0 colordown : the color of the lines where close1 < close0 alpha : bar transparency """ r,g,b = colorConverter.to_rgb(colorup) colorup = r,g,b,alpha r,g,b = colorConverter.to_rgb(colordown) colordown = r,g,b,alpha colord = { True : colorup, False : colordown, } dates, opens, closes, highs, lows, volumes = zip(*quotes) colors = [colord[close1>=close0] for close0, close1 in zip(closes[:-1], closes[1:]) if close0!=-1 and close1 !=-1] colors.insert(0,colord[closes[0]>=opens[0]]) right = width/2.0 left = -width/2.0 bars = [ ( (left, 0), (left, volume), (right, volume), (right, 0)) for d, open, close, high, low, volume in quotes] sx = ax.figure.dpi * Value(1/72.0) # scale for points sy = (ax.bbox.ur().y() - ax.bbox.ll().y()) / (ax.viewLim.ur().y() - ax.viewLim.ll().y()) barTransform = scale_sep_transform(sx,sy) dates = [d for d, open, close, high, low, volume in quotes] offsetsBars = [(d, 0) for d in dates] useAA = 0, # use tuple here lw = 0.5, # and here barCollection = PolyCollection(bars, facecolors = colors, edgecolors = ( (0,0,0,1), ), antialiaseds = useAA, linewidths = lw, offsets = offsetsBars, transOffset = ax.transData, ) barCollection.set_transform(barTransform) minx, maxx = (min(dates), max(dates)) miny = 0 maxy = max([volume for d, open, close, high, low, volume in quotes]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) #print 'datalim', ax.dataLim.get_bounds() #print 'viewlim', ax.viewLim.get_bounds() ax.add_collection(barCollection) ax.autoscale_view() return barCollection
def volume_overlay(ax, opens, closes, volumes, colorup='k', colordown='r', width=4, alpha=1.0): """ Add a volume overlay to the current axes. The opens and closes are used to determine the color of the bar. -1 is missing. If a value is missing on one it must be missing on all ax : an Axes instance to plot to width : the bar width in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open alpha : bar transparency """ r,g,b = colorConverter.to_rgb(colorup) colorup = r,g,b,alpha r,g,b = colorConverter.to_rgb(colordown) colordown = r,g,b,alpha colord = { True : colorup, False : colordown, } colors = [colord[open<close] for open, close in zip(opens, closes) if open!=-1 and close !=-1] right = width/2.0 left = -width/2.0 bars = [ ( (left, 0), (left, v), (right, v), (right, 0)) for v in volumes if v != -1 ] sx = ax.figure.dpi * Value(1/72.0) # scale for points sy = (ax.bbox.ur().y() - ax.bbox.ll().y()) / (ax.viewLim.ur().y() - ax.viewLim.ll().y()) barTransform = scale_sep_transform(sx,sy) offsetsBars = [ (i, 0) for i,v in enumerate(volumes) if v != -1 ] barCollection = PolyCollection(bars, facecolors = colors, edgecolors = ( (0,0,0,1), ), antialiaseds = (0,), linewidths = (0.5,), offsets = offsetsBars, transOffset = ax.transData, ) barCollection.set_transform(barTransform) minx, maxx = (0, len(offsetsBars)) miny = 0 maxy = max([v for v in volumes if v!=-1]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last return barCollection
def candlestick2(ax, opens, closes, highs, lows, width=4, colorup='k', colordown='r', alpha=0.75, ): """ Represent the open, close as a bar line and high low range as a vertical line. ax : an Axes instance to plot to width : the bar width in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open alpha : bar transparency return value is lineCollection, barCollection """ # note this code assumes if any value open, close, low, high is # missing they all are missing right = width/2.0 left = -width/2.0 barVerts = [ ( (left, 0), (left, close-open), (right, close-open), (right, 0) ) for open, close in zip(opens, closes) if open != -1 and close!=-1 ] rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1 ] offsetsBars = [ (i, open) for i,open in zip(xrange(len(opens)), opens) if open != -1 ] sx = ax.figure.dpi * Value(1/72.0) # scale for points sy = (ax.bbox.ur().y() - ax.bbox.ll().y()) / (ax.viewLim.ur().y() - ax.viewLim.ll().y()) barTransform = scale_sep_transform(sx,sy) r,g,b = colorConverter.to_rgb(colorup) colorup = r,g,b,alpha r,g,b = colorConverter.to_rgb(colordown) colordown = r,g,b,alpha colord = { True : colorup, False : colordown, } colors = [colord[open<close] for open, close in zip(opens, closes) if open!=-1 and close !=-1] assert(len(barVerts)==len(rangeSegments)) assert(len(rangeSegments)==len(offsetsBars)) assert(len(offsetsBars)==len(colors)) useAA = 0, # use tuple here lw = 0.5, # and here rangeCollection = LineCollection(rangeSegments, colors = ( (0,0,0,1), ), linewidths = lw, antialiaseds = useAA, ) barCollection = PolyCollection(barVerts, facecolors = colors, edgecolors = ( (0,0,0,1), ), antialiaseds = useAA, linewidths = lw, offsets = offsetsBars, transOffset = ax.transData, ) barCollection.set_transform(barTransform) minx, maxx = (0, len(rangeSegments)) miny = min([low for low in lows if low !=-1]) maxy = max([high for high in highs if high != -1]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(barCollection) ax.add_collection(rangeCollection) return rangeCollection, barCollection
def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, colorup='k', colordown='r', ): """ Represent the time, open, close, high, low as a vertical line ranging from low to high. The left tick is the open and the right tick is the close. ax : an Axes instance to plot to ticksize : size of open and close ticks in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open return value is a list of lines added """ # note this code assumes if any value open, close, low, high is # missing they all are missing rangeSegments = [ ((i, low), (i, high)) for i, low, high in zip(xrange(len(lows)), lows, highs) if low != -1 ] # the ticks will be from ticksize to 0 in points at the origin and # we'll translate these to the i, close location openSegments = [ ((-ticksize, 0), (0, 0)) ] # the ticks will be from 0 to ticksize in points at the origin and # we'll translate these to the i, close location closeSegments = [ ((0, 0), (ticksize, 0)) ] offsetsOpen = [ (i, open) for i, open in zip(xrange(len(opens)), opens) if open != -1 ] offsetsClose = [ (i, close) for i, close in zip(xrange(len(closes)), closes) if close != -1 ] scale = ax.figure.dpi * Value(1/72.0) tickTransform = scale_transform( scale, zero()) r,g,b = colorConverter.to_rgb(colorup) colorup = r,g,b,1 r,g,b = colorConverter.to_rgb(colordown) colordown = r,g,b,1 colord = { True : colorup, False : colordown, } colors = [colord[open<close] for open, close in zip(opens, closes) if open!=-1 and close !=-1] assert(len(rangeSegments)==len(offsetsOpen)) assert(len(offsetsOpen)==len(offsetsClose)) assert(len(offsetsClose)==len(colors)) useAA = 0, # use tuple here lw = 1, # and here rangeCollection = LineCollection(rangeSegments, colors = colors, linewidths = lw, antialiaseds = useAA, ) openCollection = LineCollection(openSegments, colors = colors, antialiaseds = useAA, linewidths = lw, offsets = offsetsOpen, transOffset = ax.transData, ) openCollection.set_transform(tickTransform) closeCollection = LineCollection(closeSegments, colors = colors, antialiaseds = useAA, linewidths = lw, offsets = offsetsClose, transOffset = ax.transData, ) closeCollection.set_transform(tickTransform) minx, maxx = (0, len(rangeSegments)) miny = min([low for low in lows if low !=-1]) maxy = max([high for high in highs if high != -1]) corners = (minx, miny), (maxx, maxy) ax.update_datalim(corners) ax.autoscale_view() # add these last ax.add_collection(rangeCollection) ax.add_collection(openCollection) ax.add_collection(closeCollection) return rangeCollection, openCollection, closeCollection
lineprops = dict(linewidth=1, color='black', linestyle='-') fig = figure() ax = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # The normal matplotlib transformation is the view lim bounding box # (ax.viewLim) to the axes bounding box (ax.bbox). Where are going to # define a new transform by defining a new input bounding box. See the # matplotlib.transforms module helkp for more information on # transforms # This bounding reuses the x data of the viewLim for the xscale -10 to # 10 on the y scale. -10 to 10 means that a signal with a min/max # amplitude of 10 will span the entire vertical extent of the axes scale = 10 boxin = Bbox(Point(ax.viewLim.ll().x(), Value(-scale)), Point(ax.viewLim.ur().x(), Value(scale))) # height is a lazy value height = ax.bbox.ur().y() - ax.bbox.ll().y() boxout = Bbox(Point(ax.bbox.ll().x(), Value(-0.5) * height), Point(ax.bbox.ur().x(), Value(0.5) * height)) # matplotlib transforms can accepts an offset, which is defined as a # point and another transform to map that point to display. This # transform maps x as identity and maps the 0-1 y interval to the # vertical extent of the yaxis. This will be used to offset the lines # and ticks vertically
def rand_val(N = 1): if N==1: return Value(rand()) else: return [Value(val) for val in rand(N)]
# Timing tests -- print time per plot TIME_PY = 1 TIME_EXT = 1 ################# # Test Parameters ################# # Bounding box to use in testing ll_x = 320 ll_y = 240 ur_x = 640 ur_y = 480 BBOX = Bbox(Point(Value(ll_x), Value(ll_y)), Point(Value(ur_x), Value(ur_y))) # Number of iterations for timing NITERS = 25 ############################################################################### # # Testing framework # def time_loop(function, args): i = 0
def cla(self): """ Clear the current axes """ self._get_lines = _process_plot_var_args(self) self._get_patches_for_fill = _process_plot_var_args(self, 'fill') self._gridOn = matplotlib.rcParams['polaraxes.grid'] self.thetagridlabels = [] self.thetagridlines = [] self.rgridlabels = [] self.rgridlines = [] self.lines = [] self.images = [] self.patches = [] self.artists = [] self.collections = [] self.texts = [] # text in axis coords self.legend_ = None self.grid(self._gridOn) self.title = Text( x=0.5, y=1.05, text='', fontproperties=FontProperties( size=matplotlib.rcParams['axes.titlesize']), verticalalignment='bottom', horizontalalignment='center', ) self.title.set_transform(self.transAxes) self._set_artist_props(self.title) self.thetas = N.linspace(0, 2 * N.pi, self.RESOLUTION) verts = list(zip(self.thetas, N.ones(self.RESOLUTION))) self.axesPatch = Polygon( verts, facecolor=self._axisbg, edgecolor=matplotlib.rcParams['axes.edgecolor'], ) self.axesPatch.set_figure(self.figure) self.axesPatch.set_transform(self.transData) self.axesPatch.set_linewidth(matplotlib.rcParams['axes.linewidth']) self.axison = True self.rintv = Interval(Value(0), Value(1)) self.rintd = Interval(Value(0), Value(1)) self.rformatter = ScalarFormatter() self.rformatter.set_view_interval(self.rintv) self.rformatter.set_data_interval(self.rintd) class RadialLocator(AutoLocator): 'enforce strictly positive radial ticks' def __call__(self): ticks = AutoLocator.__call__(self) return [t for t in ticks if t > 0] self.rlocator = RadialLocator() self.rlocator.set_view_interval(self.rintv) self.rlocator.set_data_interval(self.rintd) self.theta_angles = N.arange(0, 360, 45) self.theta_labels = ['E', 'N-E', 'N', 'N-W', 'W', 'S-W', 'S', 'S-E'] self.set_thetagrids(angles=self.theta_angles, labels=self.theta_labels) self._info = {'dir': list(), 'bins': list(), 'table': list()} self.patches_list = list()
# working directly with renderer and graphics contexts primitives from matplotlib.font_manager import FontProperties from matplotlib.backends.backend_agg import RendererAgg from matplotlib.transforms import Value # a 400x400 canvas at 72dpi canvas dpi = Value(72.0) o = RendererAgg(400, 400, dpi) # the graphics context gc = o.new_gc() # draw the background white gc.set_foreground('w') face = (1, 1, 1) # white o.draw_rectangle(gc, face, 0, 0, 400, 400) # the gc's know about color strings, and can handle any matplotlib # color arguments (hex strings, rgb, format strings, etc) gc.set_foreground('g') gc.set_linewidth(4) face = (1, 0, 0) # must be rgb o.draw_rectangle(gc, face, 10, 50, 100, 200) # draw a translucent ellipse rgb = (0, 0, 1) gc.set_alpha(0.5) o.draw_arc(gc, rgb, 100, 100, 100, 100, 360, 360, 0) # draw a dashed line gc.set_dashes(0, [5, 10])
ll = Point( Value(10), Value(10) ) ur = Point( Value(200), Value(40) ) bbox = Bbox(ll, ur) assert(bbox.xmin()==10) assert(bbox.width()==190) assert(bbox.height()==30) ll.x().set(12.0) assert(bbox.xmin()==12) assert(bbox.width()==188) assert(bbox.height()==30) a = Value(10) b = Value(0) c = Value(0) d = Value(20) tx = Value(-10) ty = Value(-20) affine = Affine(a,b,c,d,tx,ty) # test transformation of xy tuple x, y = affine.xy_tup( (10,20) ) assert(x==90) assert(y==380) # test transformation of sequence of xy tuples xy = affine.seq_xy_tups( ( (10,20), (20,30), ) ) assert(xy[0] == (90, 380))
hist(im, 100) xticks([-1, -.5, 0, .5, 1]) yticks([]) xlabel('intensity') ylabel('MRI density') if 1: # plot the EEG # load the data numSamples, numRows = 800, 4 data = fromstring(file('data/eeg.dat', 'rb').read(), float) data.shape = numSamples, numRows t = arange(numSamples) / float(numSamples) * 10.0 ticklocs = [] ax = subplot(212) boxin = Bbox(Point(ax.viewLim.ll().x(), Value(-20)), Point(ax.viewLim.ur().x(), Value(20))) height = ax.bbox.ur().y() - ax.bbox.ll().y() boxout = Bbox(Point(ax.bbox.ll().x(), Value(-1) * height), Point(ax.bbox.ur().x(), Value(1) * height)) transOffset = get_bbox_transform( unit_bbox(), Bbox(Point(Value(0), ax.bbox.ll().y()), Point(Value(1), ax.bbox.ur().y()))) for i in range(numRows):