def plot_2d_graph(self, data_frame, gp, chart_type): if gp is None: gp = GraphProperties() if gp.chart_type is None and chart_type is None: chart_type = 'line' if gp.resample is not None: data_frame = data_frame.asfreq(gp.resample) self.apply_style_sheet(gp) # create figure & add a subplot fig = plt.figure(figsize = ((gp.width * gp.scale_factor)/gp.dpi, (gp.height * gp.scale_factor)/gp.dpi), dpi = gp.dpi) ax = fig.add_subplot(111) if gp.x_title != '': ax.set_xlabel(gp.x_title) if gp.y_title != '': ax.set_ylabel(gp.y_title) plt.xlabel(gp.x_title) plt.ylabel(gp.y_title) fig.suptitle(gp.title, fontsize = 14 * gp.scale_factor) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset = False) ax.yaxis.set_major_formatter(y_formatter) # create a second y axis if necessary ax2 = [] if gp.y_axis_2_series != []: ax2 = ax.twinx() # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) # matplotlib 1.5 try: cyc = matplotlib.rcParams['axes.prop_cycle'] color_cycle = [x['color'] for x in cyc] except KeyError: # pre 1.5 pass # color_cycle = matplotlib.rcParams['axes.color_cycle'] bar_ind = np.arange(0, len(data_frame.index)) # for bar charts, create a proxy x-axis (then relabel) xd, bar_ind, has_bar, no_of_bars = self.get_bar_indices(data_frame, gp, chart_type, bar_ind) # plot the lines (using custom palettes as appropriate) try: # get all the correct colors (and construct gradients if necessary eg. from 'blues') color_spec = self.create_color_list(gp, data_frame) # for stacked bar yoff_pos = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart yoff_neg = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart zeros = np.zeros(len(data_frame.index.values)) # for bar chart bar_space = 0.2 bar_width = (1 - bar_space) / (no_of_bars) bar_index = 0 has_matrix = False # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): if gp.chart_type is not None: if isinstance(gp.chart_type, list): chart_type = gp.chart_type[i] else: chart_type = gp.chart_type if chart_type == 'heatmap': # TODO experimental! # ax.set_frame_on(False) ax.pcolor(data_frame, cmap=plt.cm.Blues, alpha=0.8) # plt.colorbar() has_matrix = True break label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, gp.y_axis_2_series) yd = data_frame.ix[:,i] if color_spec[i] is None: color_spec[i] = color_cycle[i % len(color_cycle)] if (chart_type == 'line'): linewidth_t = self.get_linewidth(label, gp.linewidth, gp.linewidth_2, gp.linewidth_2_series) if linewidth_t is None: linewidth_t = matplotlib.rcParams['axes.linewidth'] ax_temp.plot(xd, yd, label = label, color = color_spec[i], linewidth = linewidth_t) elif(chart_type == 'bar'): # for multiple bars we need to allocate space properly bar_pos = [k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0,len(bar_ind))] ax_temp.bar(bar_pos, yd, bar_width, label = label, color = color_spec[i]) bar_index = bar_index + 1 elif(chart_type == 'stacked'): bar_pos = [k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0,len(bar_ind))] yoff = np.where(yd > 0, yoff_pos, yoff_neg) ax_temp.bar(bar_pos, yd, label = label, color = color_spec[i], bottom = yoff) yoff_pos = yoff_pos + np.maximum(yd, zeros) yoff_neg = yoff_neg + np.minimum(yd, zeros) # bar_index = bar_index + 1 elif(chart_type == 'scatter'): ax_temp.scatter(xd, yd, label = label, color = color_spec[i]) if gp.line_of_best_fit is True: self.trendline(ax_temp, xd.values, yd.values, order=1, color= color_spec[i], alpha=1, scale_factor = gp.scale_factor) # format X axis self.format_x_axis(ax, data_frame, gp, has_bar, bar_ind, has_matrix) except: pass if gp.display_source_label == True: ax.annotate('Source: ' + gp.source, xy = (1, 0), xycoords='axes fraction', fontsize=7 * gp.scale_factor, xytext=(-5 * gp.scale_factor, 10 * gp.scale_factor), textcoords='offset points', ha='right', va='top', color = gp.source_color) if gp.display_brand_label == True: self.create_brand_label(ax, anno = gp.brand_label, scale_factor = gp.scale_factor) leg = [] leg2 = [] loc = 'best' # if we have two y-axis then make sure legends are in opposite corners if ax2 != []: loc = 2 try: leg = ax.legend(loc = loc, prop={'size':10 * gp.scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 != []: leg2 = ax2.legend(loc = 1, prop={'size':10 * gp.scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend is False: if leg != []: leg.remove() if leg2 != []: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass ####### various matplotlib converters are unstable # convert to D3 format with mpld3 try: # output matplotlib charts externally to D3 based libraries import mpld3 if gp.display_mpld3 == True: mpld3.save_d3_html(fig, gp.html_file_output) mpld3.show(fig) except: pass # FRAGILE! convert to Bokeh format # better to use direct Bokeh renderer try: if (gp.convert_matplotlib_to_bokeh == True): from bokeh.plotting import output_file, show from bokeh import mpl output_file(gp.html_file_output) show(mpl.to_bokeh()) except: pass # FRAGILE! convert matplotlib chart to Plotly format # recommend using AdapterCufflinks instead to directly plot to Plotly try: import plotly.plotly as py import plotly import plotly.tools as tls if gp.convert_matplotlib_to_plotly == True: plotly.tools.set_credentials_file(username = gp.plotly_username, api_key = gp.plotly_api_key) py_fig = tls.mpl_to_plotly(fig, strip_style = True) plot_url = py.plot_mpl(py_fig, filename = gp.plotly_url) except: pass # display in matplotlib window try: if GraphicsConstants.plotfactory_silent_display == True: return fig elif gp.silent_display == False: plt.show() else: return fig except: pass
def plot_2d_graph(self, data_frame, gp, type): matplotlib.rcdefaults() # set the matplotlib style sheet plt.style.use(Constants().plotfactory_pythalesians_style_sheet[Constants().plotfactory_default_stylesheet]) if hasattr(gp, 'style_sheet'): plt.style.use(Constants().plotfactory_pythalesians_style_sheet[gp.style_sheet]) scale_factor = Constants().plotfactory_scale_factor if hasattr(gp, 'scale_factor'): scale_factor = gp.scale_factor dpi = Constants().plotfactory_dpi if hasattr(gp, 'dpi'): dpi = gp.dpi width = Constants().plotfactory_width; height = Constants().plotfactory_height if hasattr(gp, 'width'): width = gp.width if hasattr(gp, 'height'): width = gp.height fig = plt.figure(figsize = ((width * scale_factor)/dpi, (height * scale_factor)/dpi), dpi = dpi) # add a subplot ax = fig.add_subplot(111) matplotlib.rcParams.update({'font.size': matplotlib.rcParams['font.size'] * scale_factor}) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset = False) ax.yaxis.set_major_formatter(y_formatter) y_axis_2_series = [] ax2 = [] color_2_series = [] linewidth_2_series = [] if hasattr(gp, 'resample'): data_frame = data_frame.asfreq(gp.resample) # create a second y axis if necessary if hasattr(gp, 'y_axis_2_series'): if gp.y_axis_2_series == []: pass else: y_axis_2_series = gp.y_axis_2_series ax2 = ax.twinx() # matplotlib.rcParams.update({'figure.subplot.right': matplotlib.rcParams['figure.subplot.right'] - 0.05}) # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) # is there a second palette? if hasattr(gp, 'color_2_series'): if hasattr(gp.color_2_series, 'values'): color_2_series = [str(x) for x in gp.color_2_series.values] else: color_2_series = [str(x) for x in gp.color_2_series] # is there a second linewidth series if hasattr(gp, 'linewidth_2_series'): if hasattr(gp.linewidth_2_series, 'values'): linewidth_2_series = [str(x) for x in gp.linewidth_2_series.values] else: linewidth_2_series = [str(x) for x in gp.linewidth_2_series] # plot the lines (using custom palettes as appropriate) try: color = []; color_2 = [] linewidth_2 = matplotlib.rcParams['axes.linewidth'] exclude_from_color = [] if hasattr(gp, 'color'): if isinstance(gp.color, list): color = gp.color else: try: color = self.create_colormap( len(data_frame.columns.values) - len(color_2_series), gp.color) except: pass if hasattr(gp, 'width'): if isinstance(gp.width, list): color = gp.color else: try: color = self.create_colormap( len(data_frame.columns.values) - len(color_2_series), gp.color) except: pass if hasattr(gp, 'color_2'): if isinstance(gp.color_2, list): color_2 = gp.color_2 else: try: color_2 = self.create_colormap(len(color_2_series), gp.color_2) except: pass if hasattr(gp, 'exclude_from_color'): if not(isinstance(gp.exclude_from_color, list)): gp.exclude_from_color = [gp.exclude_from_color] exclude_from_color = [str(x) for x in gp.exclude_from_color] if hasattr(gp, 'linewidth_2'): linewidth_2 = gp.linewidth_2 axis_1_color_index = 0 axis_2_color_index = 0 if type == 'bar': # bottom = np.cumsum(np.vstack((np.zeros(data_frame.values.shape[1]), data_frame.values)), axis=0)[:-1] # bottom = np.vstack((np.zeros((data_frame.values.shape[1],), dtype=data_frame.dtype), # np.cumsum(data_frame.values, axis=0)[:-1])) yoff = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, y_axis_2_series) color_spec, axis_1_color_index, axis_2_color_index = \ self.get_color(label, axis_1_color_index, axis_2_color_index, color, color_2, exclude_from_color, color_2_series) xd = data_frame.index; yd = data_frame.ix[:,i] if (type == 'line'): linewidth = self.get_linewidth(label, linewidth_2, linewidth_2_series) ax_temp.plot(xd, yd, label = label, color = color_spec, linewidth = linewidth) elif(type == 'bar'): ax_temp.bar(xd, yd, label = label, color = color_spec, bottom = yoff) yoff = yoff + yd elif(type == 'scatter'): ax_temp.scatter(xd, yd, label = label, color = color_spec) if hasattr(gp, 'line_of_best_fit'): if gp.line_of_best_fit == True: self.trendline(ax_temp, xd.values, yd.values, order=1, color= color_spec, alpha=1, scale_factor = scale_factor) except: pass # format X axis self.format_x_axis(ax, data_frame, gp) try: fig.suptitle(gp.title, fontsize = 14 * scale_factor) except: pass try: source = Constants().plotfactory_source source_color = 'black' display_brand_label = False if hasattr(gp, 'source'): source = gp.source display_brand_label = True if hasattr(gp, 'source_color'): source_color = self.get_color_code(gp.source_color) if display_brand_label or Constants().plotfactory_display_brand_label: ax.annotate('Source: ' + source, xy = (1, 0), xycoords='axes fraction', fontsize=7 * scale_factor, xytext=(-5 * scale_factor, 10 * scale_factor), textcoords='offset points', ha='right', va='top', color = source_color) except: pass if hasattr(gp, 'display_brand_label'): if gp.display_brand_label is True: self.create_brand_label(ax, anno = Constants().plotfactory_brand_label, scale_factor = scale_factor) else: if Constants().plotfactory_display_brand_label is True: self.create_brand_label(ax, anno = Constants().plotfactory_brand_label, scale_factor = scale_factor) leg = [] leg2 = [] loc = 'best' # if we have two y-axis then make sure legends are in opposite corners if ax2 != []: loc = 2 try: leg = ax.legend(loc = loc, prop={'size':10 * scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 is not []: leg2 = ax2.legend(loc = 1, prop={'size':10 * scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend == False: if leg is not[]: leg.remove() if leg2 is not[]: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass try: if hasattr(gp, 'silent_display'): if gp.silent_display is False: plt.show() else: plt.show() except: pass # convert to D3 format with mpld3 try: if hasattr(gp, 'html_file_output'): mpld3.save_d3_html(fig, gp.html_file_output) if hasattr(gp, 'display_mpld3'): if gp.display_mpld3 == True: mpld3.show(fig) except: pass # convert to Plotly format (fragile!) # TODO better to create Plotly graphs from scratch rather than convert from matplotlib # TODO also dependent on matplotlib version for support try: if hasattr(gp, 'plotly_url'): plotly.tools.set_credentials_file(username = Constants().plotly_username, api_key = Constants().plotly_api_key) py_fig = tls.mpl_to_plotly(fig, strip_style = True) plot_url = py.plot_mpl(py_fig, filename = gp.plotly_url) except: pass
def plot_2d_graph(self, data_frame, gp, chart_type): if gp is None: gp = GraphProperties() if gp.chart_type is None and chart_type is None: chart_type = 'line' if gp.resample is not None: data_frame = data_frame.asfreq(gp.resample) self.apply_style_sheet(gp) # create figure & add a subplot fig = plt.figure(figsize=((gp.width * gp.scale_factor) / gp.dpi, (gp.height * gp.scale_factor) / gp.dpi), dpi=gp.dpi) ax = fig.add_subplot(111) if gp.x_title != '': ax.set_xlabel(gp.x_title) if gp.y_title != '': ax.set_ylabel(gp.y_title) plt.xlabel(gp.x_title) plt.ylabel(gp.y_title) fig.suptitle(gp.title, fontsize=14 * gp.scale_factor) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) ax.yaxis.set_major_formatter(y_formatter) # create a second y axis if necessary ax2 = [] if gp.y_axis_2_series != []: ax2 = ax.twinx() # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) # matplotlib 1.5 try: cyc = matplotlib.rcParams['axes.prop_cycle'] color_cycle = [x['color'] for x in cyc] except KeyError: # pre 1.5 pass # color_cycle = matplotlib.rcParams['axes.color_cycle'] bar_ind = np.arange(0, len(data_frame.index)) # for bar charts, create a proxy x-axis (then relabel) xd, bar_ind, has_bar, no_of_bars = self.get_bar_indices( data_frame, gp, chart_type, bar_ind) # plot the lines (using custom palettes as appropriate) try: # get all the correct colors (and construct gradients if necessary eg. from 'blues') color_spec = self.create_color_list(gp, data_frame) # for stacked bar yoff_pos = np.zeros(len(data_frame.index.values) ) # the bottom values for stacked bar chart yoff_neg = np.zeros(len(data_frame.index.values) ) # the bottom values for stacked bar chart zeros = np.zeros(len(data_frame.index.values)) # for bar chart bar_space = 0.2 bar_width = (1 - bar_space) / (no_of_bars) bar_index = 0 has_matrix = False # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): if gp.chart_type is not None: if isinstance(gp.chart_type, list): chart_type = gp.chart_type[i] else: chart_type = gp.chart_type if chart_type == 'heatmap': # TODO experimental! # ax.set_frame_on(False) ax.pcolor(data_frame, cmap=plt.cm.Blues, alpha=0.8) # plt.colorbar() has_matrix = True break label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, gp.y_axis_2_series) yd = data_frame.ix[:, i] if color_spec[i] is None: color_spec[i] = color_cycle[i % len(color_cycle)] if (chart_type == 'line'): linewidth_t = self.get_linewidth(label, gp.linewidth, gp.linewidth_2, gp.linewidth_2_series) if linewidth_t is None: linewidth_t = matplotlib.rcParams['axes.linewidth'] ax_temp.plot(xd, yd, label=label, color=color_spec[i], linewidth=linewidth_t) elif (chart_type == 'bar'): # for multiple bars we need to allocate space properly bar_pos = [ k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0, len(bar_ind)) ] ax_temp.bar(bar_pos, yd, bar_width, label=label, color=color_spec[i]) bar_index = bar_index + 1 elif (chart_type == 'stacked'): bar_pos = [ k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0, len(bar_ind)) ] yoff = np.where(yd > 0, yoff_pos, yoff_neg) ax_temp.bar(bar_pos, yd, label=label, color=color_spec[i], bottom=yoff) yoff_pos = yoff_pos + np.maximum(yd, zeros) yoff_neg = yoff_neg + np.minimum(yd, zeros) # bar_index = bar_index + 1 elif (chart_type == 'scatter'): ax_temp.scatter(xd, yd, label=label, color=color_spec[i]) if gp.line_of_best_fit is True: self.trendline(ax_temp, xd.values, yd.values, order=1, color=color_spec[i], alpha=1, scale_factor=gp.scale_factor) # format X axis self.format_x_axis(ax, data_frame, gp, has_bar, bar_ind, has_matrix) except: pass if gp.display_source_label == True: ax.annotate('Source: ' + gp.source, xy=(1, 0), xycoords='axes fraction', fontsize=7 * gp.scale_factor, xytext=(-5 * gp.scale_factor, 10 * gp.scale_factor), textcoords='offset points', ha='right', va='top', color=gp.source_color) if gp.display_brand_label == True: self.create_brand_label(ax, anno=gp.brand_label, scale_factor=gp.scale_factor) leg = [] leg2 = [] loc = 'best' # if we have two y-axis then make sure legends are in opposite corners if ax2 != []: loc = 2 try: leg = ax.legend(loc=loc, prop={'size': 10 * gp.scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 != []: leg2 = ax2.legend(loc=1, prop={'size': 10 * gp.scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend is False: if leg != []: leg.remove() if leg2 != []: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass ####### various matplotlib converters are unstable # convert to D3 format with mpld3 try: # output matplotlib charts externally to D3 based libraries import mpld3 if gp.display_mpld3 == True: mpld3.save_d3_html(fig, gp.html_file_output) mpld3.show(fig) except: pass # FRAGILE! convert to Bokeh format # better to use direct Bokeh renderer try: if (gp.convert_matplotlib_to_bokeh == True): from bokeh.plotting import output_file, show from bokeh import mpl output_file(gp.html_file_output) show(mpl.to_bokeh()) except: pass # FRAGILE! convert matplotlib chart to Plotly format # recommend using AdapterCufflinks instead to directly plot to Plotly try: import plotly.plotly as py import plotly import plotly.tools as tls if gp.convert_matplotlib_to_plotly == True: plotly.tools.set_credentials_file(username=gp.plotly_username, api_key=gp.plotly_api_key) py_fig = tls.mpl_to_plotly(fig, strip_style=True) plot_url = py.plot_mpl(py_fig, filename=gp.plotly_url) except: pass # display in matplotlib window try: if Constants.plotfactory_silent_display == True: pass elif gp.silent_display == False: plt.show() except: pass
def plot_2d_graph(self, data_frame, gp, chart_type): if gp.resample is not None: data_frame = data_frame.asfreq(gp.resample) # set the matplotlib style sheet & defaults matplotlib.rcdefaults() # first search PyThalesians styles, then try matplotlib try: plt.style.use(Constants().plotfactory_pythalesians_style_sheet[gp.style_sheet]) except: plt.style.use(gp.style_sheet) matplotlib.rcParams.update({'font.size': matplotlib.rcParams['font.size'] * gp.scale_factor}) # create figure & add a subplot fig = plt.figure(figsize = ((gp.width * gp.scale_factor)/gp.dpi, (gp.height * gp.scale_factor)/gp.dpi), dpi = gp.dpi) ax = fig.add_subplot(111) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset = False) ax.yaxis.set_major_formatter(y_formatter) if gp.x_title != '': ax.set_xlabel(gp.x_title) if gp.y_title != '': ax.set_ylabel(gp.y_title) # create a second y axis if necessary ax2 = [] if gp.y_axis_2_series != []: ax2 = ax.twinx() # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) color_cycle = matplotlib.rcParams['axes.color_cycle'] bar_ind = np.arange(0, len(data_frame.index)) xd, bar_ind, has_bar, no_of_bars = self.get_bar_indices(data_frame, gp, chart_type, bar_ind) # plot the lines (using custom palettes as appropriate) try: # get all the correct colors (and construct gradients if necessary eg. from 'blues') color_spec = self.create_color_list(gp, data_frame) # for stacked bar yoff = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart # for bar chart # bar_ind = np.arange(len(data_frame.index)) # has_bar = False bar_space = 0.2 bar_width = (1 - bar_space) / (no_of_bars) bar_index = 0 # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): if chart_type is not None: if gp.chart_type is not None: if isinstance(gp.chart_type, list): chart_type = gp.chart_type[i] else: chart_type = gp.chart_type label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, gp.y_axis_2_series) yd = data_frame.ix[:,i] if (chart_type == 'line'): linewidth_t = self.get_linewidth(label, gp.linewidth, gp.linewidth_2, gp.linewidth_2_series) if linewidth_t is None: linewidth_t = matplotlib.rcParams['axes.linewidth'] ax_temp.plot(xd, yd, label = label, color = color_spec[i], linewidth = linewidth_t) elif(chart_type == 'bar'): bar_pos = [k - (1 - bar_space) / 2. + bar_index * bar_width for k in range(0,len(bar_ind))] if color_spec[i] is not None: ax_temp.bar(bar_pos, yd, bar_width, label = label, color = color_spec[i]) else: ax_temp.bar(bar_pos, yd, bar_width, label = label, color = color_cycle[i % len(color_cycle)]) bar_index = bar_index + 1 # bar_ind = bar_ind + bar_width has_bar = True elif(chart_type == 'stacked'): ax_temp.bar(xd, yd, label = label, color = color_spec[i], bottom = yoff) yoff = yoff + yd has_bar = True elif(chart_type == 'scatter'): ax_temp.scatter(xd, yd, label = label, color = color_spec[i]) if gp.line_of_best_fit is True: self.trendline(ax_temp, xd.values, yd.values, order=1, color= color_spec[i], alpha=1, scale_factor = gp.scale_factor) # format X axis self.format_x_axis(ax, data_frame, gp, has_bar, bar_ind) except: pass plt.xlabel(gp.x_title) plt.ylabel(gp.y_title) fig.suptitle(gp.title, fontsize = 14 * gp.scale_factor) if gp.display_source_label == True: ax.annotate('Source: ' + gp.source, xy = (1, 0), xycoords='axes fraction', fontsize=7 * gp.scale_factor, xytext=(-5 * gp.scale_factor, 10 * gp.scale_factor), textcoords='offset points', ha='right', va='top', color = gp.source_color) if gp.display_brand_label == True: self.create_brand_label(ax, anno = gp.brand_label, scale_factor = gp.scale_factor) leg = [] leg2 = [] loc = 'best' # if we have two y-axis then make sure legends are in opposite corners if ax2 != []: loc = 2 try: leg = ax.legend(loc = loc, prop={'size':10 * gp.scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 != []: leg2 = ax2.legend(loc = 1, prop={'size':10 * gp.scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend is False: if leg != []: leg.remove() if leg2 != []: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass ####### various matplotlib converters are unstable # convert to D3 format with mpld3 try: if gp.display_mpld3 == True: mpld3.save_d3_html(fig, gp.html_file_output) mpld3.show(fig) except: pass # FRAGILE! convert to Bokeh format # better to use direct Bokeh renderer try: if (gp.convert_matplotlib_to_bokeh == True): from bokeh.plotting import output_file, show from bokeh import mpl output_file(gp.html_file_output) show(mpl.to_bokeh()) except: pass # FRAGILE! convert matplotlib chart to Plotly format # recommend using AdapterCufflinks instead to directly plot to Plotly try: if gp.convert_matplotlib_to_plotly == True: plotly.tools.set_credentials_file(username = gp.plotly_username, api_key = gp.plotly_api_key) py_fig = tls.mpl_to_plotly(fig, strip_style = True) plot_url = py.plot_mpl(py_fig, filename = gp.plotly_url) except: pass # display in Matplotlib try: if gp.silent_display == False: plt.show() except: pass
def plot_2d_graph(self, data_frame, gp, chart_type): if gp.resample is not None: data_frame = data_frame.asfreq(gp.resample) # set the matplotlib style sheet & defaults matplotlib.rcdefaults() # first search PyThalesians styles, then try matplotlib try: plt.style.use(Constants().plotfactory_pythalesians_style_sheet[gp.style_sheet]) except: plt.style.use(gp.style_sheet) matplotlib.rcParams.update({"font.size": matplotlib.rcParams["font.size"] * gp.scale_factor}) # create figure & add a subplot fig = plt.figure( figsize=((gp.width * gp.scale_factor) / gp.dpi, (gp.height * gp.scale_factor) / gp.dpi), dpi=gp.dpi ) ax = fig.add_subplot(111) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) ax.yaxis.set_major_formatter(y_formatter) # create a second y axis if necessary ax2 = [] if gp.y_axis_2_series != []: ax2 = ax.twinx() # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) # plot the lines (using custom palettes as appropriate) try: # get all the correct colors (and construct gradients if necessary eg. from 'blues') color_spec = self.create_color_list(gp, data_frame) if type == "bar": # bottom = np.cumsum(np.vstack((np.zeros(data_frame.values.shape[1]), data_frame.values)), axis=0)[:-1] # bottom = np.vstack((np.zeros((data_frame.values.shape[1],), dtype=data_frame.dtype), # np.cumsum(data_frame.values, axis=0)[:-1])) yoff = np.zeros(len(data_frame.index.values)) # the bottom values for stacked bar chart # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): if chart_type is not None: if gp.chart_type is not None: if isinstance(gp.type, list): chart_type = gp.chart_type[i] else: chart_type = gp.chart_type label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, gp.y_axis_2_series) xd = data_frame.index yd = data_frame.ix[:, i] if chart_type == "line": linewidth_t = self.get_linewidth(label, gp.linewidth, gp.linewidth_2, gp.linewidth_2_series) if linewidth_t is None: linewidth_t = matplotlib.rcParams["axes.linewidth"] ax_temp.plot(xd, yd, label=label, color=color_spec[i], linewidth=linewidth_t) elif chart_type == "bar": ax_temp.bar(xd, yd, label=label, color=color_spec[i], bottom=yoff) yoff = yoff + yd elif chart_type == "scatter": ax_temp.scatter(xd, yd, label=label, color=color_spec[i]) if gp.line_of_best_fit is True: self.trendline( ax_temp, xd.values, yd.values, order=1, color=color_spec[i], alpha=1, scale_factor=gp.scale_factor, ) except: pass # format X axis self.format_x_axis(ax, data_frame, gp) fig.suptitle(gp.title, fontsize=14 * gp.scale_factor) if gp.display_source_label == True: ax.annotate( "Source: " + gp.source, xy=(1, 0), xycoords="axes fraction", fontsize=7 * gp.scale_factor, xytext=(-5 * gp.scale_factor, 10 * gp.scale_factor), textcoords="offset points", ha="right", va="top", color=gp.source_color, ) if gp.display_brand_label == True: self.create_brand_label(ax, anno=gp.brand_label, scale_factor=gp.scale_factor) leg = [] leg2 = [] loc = "best" # if we have two y-axis then make sure legends are in opposite corners if ax2 != []: loc = 2 try: leg = ax.legend(loc=loc, prop={"size": 10 * gp.scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 != []: leg2 = ax2.legend(loc=1, prop={"size": 10 * gp.scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend is False: if leg != []: leg.remove() if leg2 != []: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass ####### various matplotlib converters are unstable # convert to D3 format with mpld3 try: if gp.display_mpld3 == True: mpld3.save_d3_html(fig, gp.html_file_output) mpld3.show(fig) except: pass # FRAGILE! convert to Bokeh format # better to use direct Bokeh renderer try: if gp.convert_matplotlib_to_bokeh == True: from bokeh.plotting import output_file, show from bokeh import mpl output_file(gp.html_file_output) show(mpl.to_bokeh()) except: pass # FRAGILE! convert matplotlib chart to Plotly format # recommend using AdapterCufflinks instead to directly plot to Plotly try: if gp.convert_matplotlib_to_plotly == True: plotly.tools.set_credentials_file(username=gp.plotly_username, api_key=gp.plotly_api_key) py_fig = tls.mpl_to_plotly(fig, strip_style=True) plot_url = py.plot_mpl(py_fig, filename=gp.plotly_url) except: pass # display in Matplotlib try: if gp.silent_display == False: plt.show() except: pass
def plot_2d_graph(self, data_frame, gp, type): matplotlib.rcdefaults() # set the matplotlib style sheet plt.style.use(Constants().plotfactory_pythalesians_style_sheet[ Constants().plotfactory_default_stylesheet]) if hasattr(gp, 'style_sheet'): plt.style.use(Constants().plotfactory_pythalesians_style_sheet[ gp.style_sheet]) scale_factor = Constants().plotfactory_scale_factor if hasattr(gp, 'scale_factor'): scale_factor = gp.scale_factor dpi = Constants().plotfactory_dpi if hasattr(gp, 'dpi'): dpi = gp.dpi width = Constants().plotfactory_width height = Constants().plotfactory_height if hasattr(gp, 'width'): width = gp.width if hasattr(gp, 'height'): width = gp.height fig = plt.figure(figsize=((width * scale_factor) / dpi, (height * scale_factor) / dpi), dpi=dpi) # add a subplot ax = fig.add_subplot(111) matplotlib.rcParams.update( {'font.size': matplotlib.rcParams['font.size'] * scale_factor}) # format Y axis y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) ax.yaxis.set_major_formatter(y_formatter) # format X axis self.format_x_axis(ax, data_frame, gp) y_axis_2_series = [] ax2 = [] color_2_series = [] linewidth_2_series = [] # create a second y axis if necessary if hasattr(gp, 'y_axis_2_series'): if gp.y_axis_2_series == []: pass else: y_axis_2_series = gp.y_axis_2_series ax2 = ax.twinx() # matplotlib.rcParams.update({'figure.subplot.right': matplotlib.rcParams['figure.subplot.right'] - 0.05}) # do not use a grid with multiple y axes ax.yaxis.grid(False) ax2.yaxis.grid(False) # is there a second palette? if hasattr(gp, 'color_2_series'): if hasattr(gp.color_2_series, 'values'): color_2_series = [str(x) for x in gp.color_2_series.values] else: color_2_series = [str(x) for x in gp.color_2_series] # is there a second linewidth series if hasattr(gp, 'linewidth_2_series'): if hasattr(gp.linewidth_2_series, 'values'): linewidth_2_series = [ str(x) for x in gp.linewidth_2_series.values ] else: linewidth_2_series = [str(x) for x in gp.linewidth_2_series] # plot the lines (using custom palettes as appropriate) try: color = [] color_2 = [] linewidth_2 = matplotlib.rcParams['axes.linewidth'] exclude_from_color = [] if hasattr(gp, 'color'): if isinstance(gp.color, list): color = gp.color else: try: color = self.create_colormap( len(data_frame.columns.values) - len(color_2_series), gp.color) except: pass if hasattr(gp, 'width'): if isinstance(gp.width, list): color = gp.color else: try: color = self.create_colormap( len(data_frame.columns.values) - len(color_2_series), gp.color) except: pass if hasattr(gp, 'color_2'): if isinstance(gp.color_2, list): color_2 = gp.color_2 else: try: color_2 = self.create_colormap(len(color_2_series), gp.color_2) except: pass if hasattr(gp, 'exclude_from_color'): if not (isinstance(gp.exclude_from_color, list)): gp.exclude_from_color = [gp.exclude_from_color] exclude_from_color = [str(x) for x in gp.exclude_from_color] if hasattr(gp, 'linewidth_2'): linewidth_2 = gp.linewidth_2 axis_1_color_index = 0 axis_2_color_index = 0 if type == 'bar': # bottom = np.cumsum(np.vstack((np.zeros(data_frame.values.shape[1]), data_frame.values)), axis=0)[:-1] # bottom = np.vstack((np.zeros((data_frame.values.shape[1],), dtype=data_frame.dtype), # np.cumsum(data_frame.values, axis=0)[:-1])) yoff = np.zeros(len(data_frame.index.values) ) # the bottom values for stacked bar chart # some lines we should exclude from the color and use the default palette for i in range(0, len(data_frame.columns.values)): label = str(data_frame.columns[i]) ax_temp = self.get_axis(ax, ax2, label, y_axis_2_series) color_spec, axis_1_color_index, axis_2_color_index = \ self.get_color(label, axis_1_color_index, axis_2_color_index, color, color_2, exclude_from_color, color_2_series) xd = data_frame.index yd = data_frame.ix[:, i] if (type == 'line'): linewidth = self.get_linewidth(label, linewidth_2, linewidth_2_series) ax_temp.plot(xd, yd, label=label, color=color_spec, linewidth=linewidth) elif (type == 'bar'): ax_temp.bar(xd, yd, label=label, color=color_spec, bottom=yoff) yoff = yoff + yd elif (type == 'scatter'): ax_temp.scatter(xd, yd, label=label, color=color_spec) if hasattr(gp, 'line_of_best_fit'): if gp.line_of_best_fit == True: self.trendline(ax_temp, xd.values, yd.values, order=1, color=color_spec, alpha=1, scale_factor=scale_factor) except: pass try: fig.suptitle(gp.title, fontsize=14 * scale_factor) except: pass try: source = Constants().plotfactory_source source_color = 'black' display_brand_label = False if hasattr(gp, 'source'): source = gp.source display_brand_label = True if hasattr(gp, 'source_color'): source_color = self.get_color_code(gp.source_color) if display_brand_label or Constants( ).plotfactory_display_brand_label: ax.annotate('Source: ' + source, xy=(1, 0), xycoords='axes fraction', fontsize=7 * scale_factor, xytext=(-5 * scale_factor, 10 * scale_factor), textcoords='offset points', ha='right', va='top', color=source_color) except: pass if hasattr(gp, 'display_brand_label'): if gp.display_brand_label is True: self.create_brand_label( ax, anno=Constants().plotfactory_brand_label, scale_factor=scale_factor) else: if Constants().plotfactory_display_brand_label is True: self.create_brand_label( ax, anno=Constants().plotfactory_brand_label, scale_factor=scale_factor) leg = [] leg2 = [] loc = 'best' # if we have two y-axis then make sure legends are in opposite corners if ax2 != []: loc = 2 try: leg = ax.legend(loc=loc, prop={'size': 10 * scale_factor}) leg.get_frame().set_linewidth(0.0) leg.get_frame().set_alpha(0) if ax2 is not []: leg2 = ax2.legend(loc=1, prop={'size': 10 * scale_factor}) leg2.get_frame().set_linewidth(0.0) leg2.get_frame().set_alpha(0) except: pass try: if gp.display_legend == False: if leg is not []: leg.remove() if leg2 is not []: leg.remove() except: pass try: plt.savefig(gp.file_output, transparent=False) except: pass try: if hasattr(gp, 'silent_display'): if gp.silent_display is False: plt.show() else: plt.show() except: pass # convert to D3 format with mpld3 try: if hasattr(gp, 'html_file_output'): mpld3.save_d3_html(fig, gp.html_file_output) if hasattr(gp, 'display_mpld3'): if gp.display_mpld3 == True: mpld3.show(fig) except: pass # convert to Plotly format (fragile!) # TODO better to create Plotly graphs from scratch rather than convert from matplotlib # TODO also dependent on matplotlib version for support try: if hasattr(gp, 'plotly_url'): plotly.tools.set_credentials_file( username=Constants().plotly_username, api_key=Constants().plotly_api_key) py_fig = tls.mpl_to_plotly(fig, strip_style=True) plot_url = py.plot_mpl(py_fig, filename=gp.plotly_url) except: pass