def _plotMTCombined(conf, data, subject='__'): mt, time, idS, id, p = data['all'] time2 = numpy.linspace(time.min(),time.max(),30000) figname = os.path.join(grPath,subject+'_'+conf[0]+'-'+conf[1]+'_'+conf[2]+'_'+'_MTGraph_All'+grExt) figtitle = subject+' '+conf[0]+'-'+conf[1]+' '+conf[2]+'Combined replications' fig = pylab.figure() host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.set_ylabel("MT (ms)") host.set_xlabel("Time (ms)") host.axis["right"].set_visible(False) par1.axis["right"].set_visible(True) par1.set_ylabel("ID") par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) fig.add_axes(host) sigmoidArr = sigmoid(p,time2) t2 = time2[numpy.where(abs(sigmoidArr - (sigmoidArr.min() + sigmoidArr.max())/2) < eps2)[0]] #t50 = abs(t2-time2.max()) t50 = t2 if isinstance(t50, numpy.ndarray): t50 = t50.mean() #host.set_ylim(mt.min(),mt.max()) if conf[0] == '4': host.set_ylim(200,900) host.set_xlim(0, 70000) else: host.set_ylim(200,1600) host.set_xlim(0, 90000) host.scatter(time,mt,s=0.1,marker='x',linewidth=0.1,label="MT") host.plot(time2,sigmoid(p,time2),'-r',linewidth=1.5,label="Fitted MT") par1.scatter(time, id, s=1, c='r',label="ID", linewidth=0.5) msg = "MT50 = %f" % t50 host.text( 0.3 , 0.95, msg, fontsize = 8,\ horizontalalignment='left', verticalalignment='center',\ transform = host.transAxes) host.vlines(t50,mt.min(),mt.max()) #host.set_ylim(mt.min(),mt.max()) if conf[0] == '4': host.set_ylim(200,900) host.set_xlim(0, 70000) else: host.set_ylim(200,1600) host.set_xlim(0, 90000) par1.set_ylim(min(int(conf[0]),int(conf[1])),max(int(conf[0]),int(conf[1]))) #host.legend() host.set_title(figtitle) fig.savefig(figname) pylab.close()
if __name__ == "__main__": fig = plt.figure(1) host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) par2 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.parasites.append(par2) host.set_ylabel("Density") host.set_xlabel("Distance") host.axis["right"].set_visible(False) par1.axis["right"].set_visible(True) par1.set_ylabel("Temperature") par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) par2.set_ylabel("Velocity") offset = (60, 0) new_axisline = par2._grid_helper.new_fixed_axis par2.axis["right2"] = new_axisline(loc="right", axes=par2, offset=offset) fig.add_axes(host) host.set_xlim(0, 2) host.set_ylim(0, 2) host.set_xlabel("Distance")
if __name__ == "__main__": fig = plt.figure(1) host = HostAxes(fig, [0.15, 0.1, 0.65, 0.8]) par1 = ParasiteAxes(host, sharex=host) par2 = ParasiteAxes(host, sharex=host) host.parasites.append(par1) host.parasites.append(par2) host.set_ylabel("Density") host.set_xlabel("Distance") host.axis["right"].set_visible(False) par1.axis["right"].set_visible(True) par1.set_ylabel("Temperature") par1.axis["right"].major_ticklabels.set_visible(True) par1.axis["right"].label.set_visible(True) par2.set_ylabel("Velocity") offset = (60, 0) new_axisline = par2._grid_helper.new_fixed_axis par2.axis["right2"] = new_axisline(loc="right", axes=par2, offset=offset) fig.add_axes(host) host.set_xlim(0, 2)
def new_axis(fig, hostax, off=50, loc='bottom', ticks=None, wsadd=0.1, label='', sharex=False, sharey=False): """Make a new axis line using mpl_toolkits.axes_grid's SubplotHost and ParasiteAxes. The new axis line will be an instance of ParasiteAxes attached to `hostax`. You can do twinx()/twiny() type axis (off=0) or completely free-standing axis lines (off > 0). Parameters ---------- fig : mpl Figure hostax : Instance of matplotlib.axes.HostAxesSubplot. This is the subplot of the figure `fig` w.r.t which all new axis lines are placed. See make_axes_grid_fig(). off : offset in points, used with parax.get_grid_helper().new_fixed_axis loc : one of 'left', 'right', 'top', 'bottom', where to place the new axis line ticks : sequence of ticks (numbers) wsadd : Whitespace to add at the location `loc` to make space for the new axis line (only useful if off > 0). The number is a relative unit and is used to change the bounding box: hostax.get_position(). label : str, xlabel (ylabel) for 'top','bottom' ('left', 'right') sharex, sharey : bool, share xaxis (yaxis) with `hostax` Returns ------- (fig, hostax, parax) fig : the Figure hostax : the hostax parax : the new ParasiteAxes instance Notes ----- * The sharex/sharey thing may not work correctly. """ # Create ParasiteAxes, an ax which overlays hostax. if sharex and sharey: parax = ParasiteAxes(hostax, sharex=hostax, sharey=hostax) elif sharex: parax = ParasiteAxes(hostax, sharex=hostax) elif sharey: parax = ParasiteAxes(hostax, sharey=hostax) else: parax = ParasiteAxes(hostax) hostax.parasites.append(parax) # If off != 0, the new axis line will be detached from hostax, i.e. # completely "free standing" below (above, left or right of) the main ax # (hostax), so we don't need anything visilbe from it b/c we create a # new_fixed_axis from this one with an offset anyway. We only need to # activate the label. for _loc in ['left', 'right', 'top', 'bottom']: parax.axis[_loc].set_visible(False) parax.axis[_loc].label.set_visible(True) # Create axis line. Free-standing if off != 0, else overlaying one of hostax's # axis lines. In fact, with off=0, one simulates twinx/y(). new_axisline = parax.get_grid_helper().new_fixed_axis if loc == 'top': offset = (0, off) parax.set_xlabel(label) elif loc == 'bottom': offset = (0, -off) parax.set_xlabel(label) elif loc == 'left': offset = (-off, 0) parax.set_ylabel(label) elif loc == 'right': offset = (off, 0) parax.set_ylabel(label) newax = new_axisline(loc=loc, offset=offset, axes=parax) # name axis lines: bottom2, bottom3, ... n=2 while parax.axis.has_key(loc + str(n)): n += 1 parax.axis[loc + str(n)] = newax # set ticks if ticks is not None: newax.axis.set_ticks(ticks) # Read out whitespace at the location (loc = 'top', 'bottom', 'left', # 'right') and adjust whitespace. # # indices of the values in the array returned by ax.get_position() bbox_idx = dict(left=[0,0], bottom=[0,1], right=[1,0], top=[1,1]) old_pos = np.array(hostax.get_position())[bbox_idx[loc][0], bbox_idx[loc][1]] if loc in ['top', 'right']: new_ws = old_pos - wsadd else: new_ws = old_pos + wsadd # hack ... cmd = "fig.subplots_adjust(%s=%f)" %(loc, new_ws) eval(cmd) return fig, hostax, parax
def runner (parser, options, args): options = Options (options) run_method = getattr(parser, 'run_method', 'subcommand') if os.name=='posix' and run_method == 'subprocess': print 'This script cannot be run using subprocess method. Choose subcommand to continue.' return if args: if len (args)==1: if options.input_path: print >> sys.stderr, "WARNING: overwriting input path %r with %r" % (options.input_path, args[0]) options.input_path = args[0] if options.input_path is None: parser.error('Expected --input-path but got nothing') data, titles = RowFile (options.input_path).read(with_titles = True) if options.print_keys: print 'rowfile keys:' + ', '.join(data.keys()) print 'length:', len(data[data.keys()[0]] or []) return if not options.x_keys and not options.y_keys: options.x_keys = titles[0] options.y_keys = ','.join(titles[1:]) parser.save_options(options, []) if not options.x_keys or not options.y_keys: print 'No x or y keys specified for the plot.' return x_keys = [str (k).strip() for k in options.x_keys.split (',')] y_keys = [str (k).strip() for k in options.y_keys.split (',')] from mpl_toolkits.axes_grid.parasite_axes import HostAxes, ParasiteAxes import matplotlib.pyplot as plt fig = plt.figure(1, figsize=(12,6)) host = HostAxes(fig, [0.1, 0.1, 0.55, 0.8]) host.axis["right"].set_visible(False) fig.add_axes(host) host.set_title(options.input_path) legend_list = [] axes_ylim = [] plot_axes = [] for x_key in x_keys: x_data = data.get(x_key) if x_data is None: print 'Rowfile does not contain a column named %r' % (x_key) continue offset = 20 host.set_xlabel(x_key) for y_key in y_keys: plot_str = 'plot' if y_key.startswith('log:'): y_key = y_key[4:] plot_str = 'semilogy' y_data = data.get(y_key) if y_data is None: print 'Rowfile does not contain a column named %r' % (y_key) continue if axes_ylim: ax = ParasiteAxes(host, sharex=host) host.parasites.append(ax) #ax.axis["right"].set_visible(True) #ax.axis["right"].major_ticklabels.set_visible(True) #ax.axis["right"].label.set_visible(True) new_axisline = ax._grid_helper.new_fixed_axis ax_line = ax.axis["right2"] = new_axisline(loc="right", axes=ax, offset=(offset,0)) if plot_str=='semilogy': offset += 60 else: offset += 40 else: ax = host ax_line = ax.axis['left'] ax.set_ylabel(y_key) p, = getattr(ax, plot_str)(x_data, y_data, label = y_key) axes_ylim.append((ax, min (y_data), max (y_data))) plot_axes.append((p, ax_line)) [ax.set_ylim(mn,mx) for ax,mn,mx in axes_ylim] #[ax_line.label.set_color (p.get_color()) for p, ax in plot_axes] host.legend() def on_keypressed(event): key = event.key if key=='q': sys.exit(0) fig.canvas.mpl_connect('key_press_event', on_keypressed) plt.draw() output_path = options.get (output_path='') if output_path: plt.savefig (output_path) print 'wrote',output_path sys.exit(0) plt.show()