def define_new_cycle(color_period=None, color_frequency=None, color_cycle=default_color_cycle, marker=[',', 'o', 'v', '+', 'x'], **kwargs): if (color_frequency is not None) and (color_period is not None): raise AttributeError("Only a color period or frequency may be set") style_cycles = {'marker': marker, **kwargs} prop_cycle = 1 # plt.rcParams['axes.prop_cycle'] for prop in style_cycles: tmp = {} tmp[prop] = style_cycles[prop] prop_cycle = prop_cycle * cycler(**tmp) if color_period is not None: dict_props = {prop: [] for prop in style_cycles} for i, props in zip(range(color_period), prop_cycle): for prop in props: dict_props[prop].append(props[prop]) if color_frequency is not None: color_cycle = cycler( color=color_cycle.by_key()['color'][:color_frequency]) if (color_frequency is None) and (color_period is None): prop_cycle_sized = color_cycle * prop_cycle elif (color_period is not None) and (color_period > 1): prop_cycle_sized = color_cycle * cycler(**dict_props) elif (color_frequency is not None) and (color_frequency > 1): prop_cycle_sized = prop_cycle * color_cycle elif color_period == 1 or color_frequency == 1: prop_cycle_sized = color_cycle else: raise AttributeError( f"`color_period` cannot be {color_period}, must be >=1 or None") return prop_cycle_sized
def save(self, report_dir: str = ""): """Saves document to the file""" plt.style.use(['tearsheet']) # Change the color map for the plots to use 10 different colors hex_colors = [plt.colors.rgb2hex(c) for c in plt.cm.tab10(range(10))] plt.rcParams['axes.prop_cycle'] = cycler(color=hex_colors) file_name = "%Y_%m_%d-%H%M {}.pdf".format(self.title) file_name = datetime.now().strftime(file_name) if not file_name.endswith(".pdf"): file_name = "{}.pdf".format(file_name) return self.pdf_exporter.generate([self.document], report_dir, file_name)
def Question2Plot(U_X, U_Y, Y_Coord, n, m): #Set colour cycle mpl.rcParams['axes.prop_cycle'] = cycler('color', ['r', 'b', 'g']) #Plot X-velocity vs y-height py.figure(2) Label = str(m) + "X" + str(n) + " Node Mesh" py.plot(U_X, Y_Coord, label=Label) py.title("X-Velocity at x = 0.5") py.xlabel("Y-Coordinate (m)") py.ylabel("X-Velocity (m/s)") py.legend() #Plot Y-velocity vs y-height py.figure(3) Label = str(m) + "X" + str(n) + " Node Mesh" py.plot(U_Y, Y_Coord, label=Label) py.title("Y-Velocity at x = 0.5") py.xlabel("Y-Coordniate (m)") py.ylabel("Y-Velocity (m/s)") py.legend()
def make_report_plots(expname, default, center, index, index_test, reg=False, stop=False): savedir = os.path.join('out', 'report', 'img') os.makedirs(savedir, exist_ok=True) rank = comm.get_rank() if rank == 0: # Set rc parameters plt.rc('font', size=10) plt.rc('xtick', labelsize=9) plt.rc('ytick', labelsize=9) plt.rc('lines', lw=1.0) plt.rc('figure', figsize=(4.5, 2)) plt.rc('legend', fancybox=False, loc='upper right', fontsize='small', borderaxespad=0) plt.tick_params(which='major', labelsize='small') from matplotlib import rcsetup nipy = plt.cm.get_cmap(name='nipy_spectral') idx = 1 - np.linspace(0, 1, 20) plt.rc('axes', prop_cycle=rcsetup.cycler('color', nipy(idx))) if stop: make_stop_plot(expname, default, center, savedir) else: if reg: make_regression_plot(expname, default, center, index, index_test, savedir) else: make_error_plot(expname, default, center, savedir) make_thm1_plot(expname, default, center, savedir)
def __configure(self, n_wait, dataset_name, plots, n_learners): """ __configure This function will verify which subplots it should create. For each one of those, it will initialize all relevant objects to keep track of the plotting points. Basic structures needed to keep track of plot values (for each subplot) are: lists of values and matplotlib's line objects. The __configure function will also initialize each subplot with the correct name and setup the axis. The subplot size will self adjust to each screen size, so that data can be better viewed in different contexts. Parameters ---------- n_wait: int (Default: 200) The interval between each plot point. dataset_name: string (Default: 'Unnamed graph') The title of the plot. Algorithmically it's not important. plots: list A list containing all the subplots to plot. Can be any of: 'performance', 'kappa', 'scatter', 'hamming_score', 'hamming_loss', 'exact_match', 'j_index', 'mean_square_error', 'mean_absolute_error', 'true_vs_predicts', 'kappa_t', 'kappa_m' n_learners: int The number of learners to compare. """ font_size_small = 8 font_size_medium = 10 font_size_large = 12 plt.rc('font', size=font_size_small) # controls default text sizes plt.rc('axes', titlesize=font_size_medium) # font size of the axes title plt.rc('axes', labelsize=font_size_small) # font size of the x and y labels plt.rc('xtick', labelsize=font_size_small) # font size of the tick labels plt.rc('ytick', labelsize=font_size_small) # font size of the tick labels plt.rc('legend', fontsize=font_size_small) # legend font size plt.rc('figure', titlesize=font_size_large) # font size of the figure title warnings.filterwarnings("ignore", ".*GUI is implemented.*") warnings.filterwarnings("ignore", ".*left==right.*") warnings.filterwarnings("ignore", ".*Passing 1d.*") self.n_wait = n_wait self.dataset_name = dataset_name self.plots = plots self.n_learners = n_learners self.X = [] plt.ion() self.fig = plt.figure(figsize=(9, 5)) self.fig.suptitle(dataset_name) self.num_plots = len(self.plots) base = 11 + self.num_plots * 100 # 3-digit integer describing the position of the subplot. self.fig.canvas.set_window_title('scikit-multiflow') if 'performance' in self.plots: self.partial_performance = [[] for _ in range(self.n_learners)] self.global_performance = [[] for _ in range(self.n_learners)] self.subplot_performance = self.fig.add_subplot(base) self.subplot_performance.set_title('Accuracy') self.subplot_performance.set_ylabel('Performance ratio') base += 1 self.line_partial_performance = [None for _ in range(self.n_learners)] self.line_global_performance = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_performance[i], = self.subplot_performance.plot( self.X, self.partial_performance[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_performance[i], = self.subplot_performance.plot( self.X, self.global_performance[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_performance[i]) handle.append(self.line_global_performance[i]) self._set_fig_legend(handle) self.subplot_performance.set_ylim(0, 1) if 'kappa' in self.plots: self.partial_kappa = [[] for _ in range(self.n_learners)] self.global_kappa = [[] for _ in range(self.n_learners)] self.subplot_kappa = self.fig.add_subplot(base) self.subplot_kappa.set_title('Kappa') self.subplot_kappa.set_ylabel('Kappa statistic') base += 1 self.line_partial_kappa = [None for _ in range(self.n_learners)] self.line_global_kappa = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_kappa[i], = self.subplot_kappa.plot( self.X, self.partial_kappa[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_kappa[i], = self.subplot_kappa.plot( self.X, self.global_kappa[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_kappa[i]) handle.append(self.line_global_kappa[i]) self._set_fig_legend(handle) self.subplot_kappa.set_ylim(-1, 1) if 'kappa_t' in self.plots: self.partial_kappa_t = [[] for _ in range(self.n_learners)] self.global_kappa_t = [[] for _ in range(self.n_learners)] self.subplot_kappa_t = self.fig.add_subplot(base) self.subplot_kappa_t.set_title('Kappa T') self.subplot_kappa_t.set_ylabel('Kappa T statistic') base += 1 self.line_partial_kappa_t = [None for _ in range(self.n_learners)] self.line_global_kappa_t = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_kappa_t[i], = self.subplot_kappa_t.plot( self.X, self.partial_kappa_t[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_kappa_t[i], = self.subplot_kappa_t.plot( self.X, self.global_kappa_t[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_kappa_t[i]) handle.append(self.line_global_kappa_t[i]) self._set_fig_legend(handle) self.subplot_kappa_t.set_ylim(-1, 1) if 'kappa_m' in self.plots: self.partial_kappa_m = [[] for _ in range(self.n_learners)] self.global_kappa_m = [[] for _ in range(self.n_learners)] self.subplot_kappa_m = self.fig.add_subplot(base) self.subplot_kappa_m.set_title('Kappa M') self.subplot_kappa_m.set_ylabel('Kappa M statistic') base += 1 self.line_partial_kappa_m = [None for _ in range(self.n_learners)] self.line_global_kappa_m = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_kappa_m[i], = self.subplot_kappa_m.plot( self.X, self.partial_kappa_m[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_kappa_m[i], = self.subplot_kappa_m.plot( self.X, self.global_kappa_m[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_kappa_m[i]) handle.append(self.line_global_kappa_m[i]) self._set_fig_legend(handle) self.subplot_kappa_m.set_ylim(-1, 1) if 'hamming_score' in self.plots: self.global_hamming_score = [[] for _ in range(self.n_learners)] self.partial_hamming_score = [[] for _ in range(self.n_learners)] self.subplot_hamming_score = self.fig.add_subplot(base) self.subplot_hamming_score.set_title('Hamming score') self.subplot_hamming_score.set_ylabel('Hamming score') base += 1 self.line_partial_hamming_score = [None for _ in range(self.n_learners)] self.line_global_hamming_score = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_hamming_score[i], = self.subplot_hamming_score.plot( self.X, self.partial_hamming_score[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_hamming_score[i], = self.subplot_hamming_score.plot( self.X, self.global_hamming_score[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_hamming_score[i]) handle.append(self.line_global_hamming_score[i]) self._set_fig_legend(handle) self.subplot_hamming_score.set_ylim(0, 1) if 'hamming_loss' in self.plots: self.global_hamming_loss = [[] for _ in range(self.n_learners)] self.partial_hamming_loss = [[] for _ in range(self.n_learners)] self.subplot_hamming_loss = self.fig.add_subplot(base) self.subplot_hamming_loss.set_title('Hamming loss') self.subplot_hamming_loss.set_ylabel('Hamming loss') base += 1 self.line_partial_hamming_loss = [None for _ in range(self.n_learners)] self.line_global_hamming_loss = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_hamming_loss[i], = self.subplot_hamming_loss.plot( self.X, self.partial_hamming_loss[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_hamming_loss[i], = self.subplot_hamming_loss.plot( self.X, self.global_hamming_loss[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_hamming_loss[i]) handle.append(self.line_global_hamming_loss[i]) self._set_fig_legend(handle) self.subplot_hamming_loss.set_ylim(0, 1) if 'exact_match' in self.plots: self.global_exact_match = [[] for _ in range(self.n_learners)] self.partial_exact_match = [[] for _ in range(self.n_learners)] self.subplot_exact_match = self.fig.add_subplot(base) self.subplot_exact_match.set_title('Exact matches') self.subplot_exact_match.set_ylabel('Exact matches') base += 1 self.line_partial_exact_match = [None for _ in range(self.n_learners)] self.line_global_exact_match = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_exact_match[i], = self.subplot_exact_match.plot( self.X, self.partial_exact_match[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_exact_match[i], = self.subplot_exact_match.plot( self.X, self.global_exact_match[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_exact_match[i]) handle.append(self.line_global_exact_match[i]) self._set_fig_legend(handle) self.subplot_exact_match.set_ylim(0, 1) if 'j_index' in self.plots: self.global_j_index = [[] for _ in range(self.n_learners)] self.partial_j_index = [[] for _ in range(self.n_learners)] self.subplot_j_index = self.fig.add_subplot(base) self.subplot_j_index.set_title('J index') self.subplot_j_index.set_ylabel('J index') base += 1 self.line_partial_j_index = [None for _ in range(self.n_learners)] self.line_global_j_index = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_j_index[i], = self.subplot_j_index.plot( self.X, self.partial_j_index[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_j_index[i], = self.subplot_j_index.plot( self.X, self.global_j_index[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_j_index[i]) handle.append(self.line_global_j_index[i]) self._set_fig_legend(handle) self.subplot_j_index.set_ylim(0, 1) if 'mean_square_error' in self.plots: self.global_mse = [[] for _ in range(self.n_learners)] self.partial_mse = [[] for _ in range(self.n_learners)] self.subplot_mse = self.fig.add_subplot(base) self.subplot_mse.set_title('Mean Squared Error') self.subplot_mse.set_ylabel('MSE') base += 1 self.line_partial_mse = [None for _ in range(self.n_learners)] self.line_global_mse = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_mse[i], = self.subplot_mse.plot( self.X, self.partial_mse[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_mse[i], = self.subplot_mse.plot( self.X, self.global_mse[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_mse[i]) handle.append(self.line_global_mse[i]) self._set_fig_legend(handle) self.subplot_mse.set_ylim(0, 1) if 'mean_absolute_error' in self.plots: self.global_mae = [[] for _ in range(self.n_learners)] self.partial_mae = [[] for _ in range(self.n_learners)] self.subplot_mae = self.fig.add_subplot(base) self.subplot_mae.set_title('Mean Absolute Error') self.subplot_mae.set_ylabel('MAE') base += 1 self.line_partial_mae = [None for _ in range(self.n_learners)] self.line_global_mae = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_partial_mae[i], = self.subplot_mae.plot( self.X, self.partial_mae[i], label='Learner {} (last {} samples)'.format(i, self.n_wait)) self.line_global_mae[i], = self.subplot_mae.plot( self.X, self.global_mae[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_partial_mae[i]) handle.append(self.line_global_mae[i]) self._set_fig_legend(handle) self.subplot_mae.set_ylim(0, 1) if 'true_vs_predicts' in self.plots: self.true_values = [] self.pred_values = [[] for _ in range(self.n_learners)] self.subplot_true_vs_predicts = self.fig.add_subplot(base) self.subplot_true_vs_predicts.set_title('True vs Predicted') self.subplot_true_vs_predicts.set_ylabel('y') self.subplot_true_vs_predicts.set_prop_cycle(cycler('color', ['c', 'm', 'y', 'k'])) base += 1 if self.task_type == 'classification': self.line_true, = self.subplot_true_vs_predicts.step(self.X, self.true_values, label='True value') else: self.line_true, = self.subplot_true_vs_predicts.plot(self.X, self.true_values, label='True value') handle = [self.line_true] self.line_pred = [None for _ in range(self.n_learners)] for i in range(self.n_learners): if self.task_type == 'classification': self.line_pred[i], = self.subplot_true_vs_predicts.step(self.X, self.pred_values[i], label='Learner {}'.format(i), linestyle='dotted') else: self.line_pred[i], = self.subplot_true_vs_predicts.plot(self.X, self.pred_values[i], label='Learner {}'.format(i), linestyle='dotted') handle.append(self.line_pred[i]) self.subplot_true_vs_predicts.legend(handles=handle) self.subplot_true_vs_predicts.set_ylim(0, 1) plt.xlabel('Samples') self.fig.subplots_adjust(hspace=.5) self.fig.tight_layout(rect=[0, .04, 1, 0.98], pad=2.6, w_pad=0.5, h_pad=1.0)
# names of keys to deprecate # the values are a tuple of (new_name, f_old_2_new, f_new_2_old) # the inverse function may be `None` _deprecated_map = { 'text.fontstyle': ('font.style', lambda x: x, None), 'text.fontangle': ('font.style', lambda x: x, None), 'text.fontvariant': ('font.variant', lambda x: x, None), 'text.fontweight': ('font.weight', lambda x: x, None), 'text.fontsize': ('font.size', lambda x: x, None), 'tick.size': ('tick.major.size', lambda x: x, None), 'svg.embed_char_paths': ('svg.fonttype', lambda x: "path" if x else "none", None), 'savefig.extension': ('savefig.format', lambda x: x, None), 'axes.color_cycle': ('axes.prop_cycle', lambda x: cycler('color', x), lambda x: [c.get('color', None) for c in x]), } _deprecated_ignore_map = {} _obsolete_set = set([ 'tk.pythoninspect', ]) _all_deprecated = set( chain(_deprecated_ignore_map, _deprecated_map, _obsolete_set)) class RcParams(dict): """ A dictionary object including validation
# names of keys to deprecate # the values are a tuple of (new_name, f_old_2_new, f_new_2_old) # the inverse function may be `None` _deprecated_map = { 'text.fontstyle': ('font.style', lambda x: x, None), 'text.fontangle': ('font.style', lambda x: x, None), 'text.fontvariant': ('font.variant', lambda x: x, None), 'text.fontweight': ('font.weight', lambda x: x, None), 'text.fontsize': ('font.size', lambda x: x, None), 'tick.size': ('tick.major.size', lambda x: x, None), 'svg.embed_char_paths': ('svg.fonttype', lambda x: "path" if x else "none", None), 'savefig.extension': ('savefig.format', lambda x: x, None), 'axes.color_cycle': ('axes.prop_cycle', lambda x: cycler('color', x), lambda x: [c.get('color', None) for c in x]), } _deprecated_ignore_map = { } _obsolete_set = set(['tk.pythoninspect', ]) _all_deprecated = set(chain(_deprecated_ignore_map, _deprecated_map, _obsolete_set)) class RcParams(dict): """ A dictionary object including validation
# coding: utf-8 # In[2]: import matplotlib.pylab as plt import matplotlib.rcsetup as rcsetup import numpy as np # rc設定カスタマイズ前 jet = plt.cm.jet fig, ax = plt.subplots() N = 20 idx = np.linspace(0, 1, N) x = np.linspace(0, 100, 200) for i in range(1, N + 1): ax.plot(x, np.sin(x) + i) ax.set_ylim(0, N + 1) # rc設定カスタマイズ後 fig2, ax2 = plt.subplots() ax2.set_prop_cycle(rcsetup.cycler('color', jet(idx))) for i in range(1, N + 1): ax2.plot(x, np.sin(x) + i) ax2.set_ylim(0, N + 1) plt.show() # In[ ]:
def __configure(self): """ This function will verify which subplots should be create. Initializing all relevant objects to keep track of the plotting points. Basic structures needed to keep track of plot values (for each subplot) are: lists of values and matplot line objects. The __configure function will also initialize each subplot with the correct name and setup the axis. The subplot size will self adjust to each screen size, so that data can be better viewed in different contexts. """ font_size_small = 8 font_size_medium = 10 font_size_large = 12 plt.rc('font', size=font_size_small) # controls default text sizes plt.rc('axes', titlesize=font_size_medium) # font size of the axes title plt.rc('axes', labelsize=font_size_small) # font size of the x and y labels plt.rc('xtick', labelsize=font_size_small) # font size of the tick labels plt.rc('ytick', labelsize=font_size_small) # font size of the tick labels plt.rc('legend', fontsize=font_size_small) # legend font size plt.rc('figure', titlesize=font_size_large) # font size of the figure title warnings.filterwarnings("ignore", ".*GUI is implemented.*") warnings.filterwarnings("ignore", ".*left==right.*") warnings.filterwarnings("ignore", ".*Passing 1d.*") self._sample_ids = [] memory_time = {} plt.ion() self.fig = plt.figure(figsize=(9, 5)) self.fig.suptitle(self.dataset_name) plot_metrics = [ m for m in self.metrics if m not in [constants.RUNNING_TIME, constants.MODEL_SIZE] ] base = 11 + len( plot_metrics ) * 100 # 3-digit integer describing the position of the subplot. self.fig.canvas.set_window_title('scikit-multiflow') # Subplots handler for metric_id in self.metrics: data_ids = self._data_dict[metric_id] self._plot_trackers[metric_id] = PlotDataTracker(data_ids) plot_tracker = self._plot_trackers[metric_id] if metric_id not in [constants.RUNNING_TIME, constants.MODEL_SIZE]: plot_tracker.sub_plot_obj = self.fig.add_subplot(base) base += 1 if metric_id == constants.TRUE_VS_PREDICTED: handle = [] plot_tracker.sub_plot_obj.set_prop_cycle( cycler('color', ['c', 'm', 'y', 'k'])) for data_id in data_ids: if data_id == constants.Y_TRUE: # True data plot_tracker.data[data_id] = [] label = 'True value' line_style = '--' line_obj = plot_tracker.line_objs if self.task_type == constants.CLASSIFICATION: line_obj[ data_id], = plot_tracker.sub_plot_obj.step( self._sample_ids, plot_tracker.data[data_id], label=label, linestyle=line_style) else: line_obj[ data_id], = plot_tracker.sub_plot_obj.plot( self._sample_ids, plot_tracker.data[data_id], label=label, linestyle=line_style) handle.append(line_obj[data_id]) else: # Predicted data plot_tracker.data[data_id] = [ [] for _ in range(self.n_models) ] plot_tracker.line_objs[data_id] = [ None for _ in range(self.n_models) ] line_obj = plot_tracker.line_objs[data_id] for i in range(self.n_models): label = 'Predicted {}'.format(self.model_names[i]) line_style = '--' if self.task_type == constants.CLASSIFICATION: line_obj[i], = plot_tracker.sub_plot_obj.step( self._sample_ids, plot_tracker.data[data_id][i], label=label, linestyle=line_style) else: line_obj[i], = plot_tracker.sub_plot_obj.plot( self._sample_ids, plot_tracker.data[data_id][i], label=label, linestyle=line_style) handle.append(line_obj[i]) plot_tracker.sub_plot_obj.legend(handles=handle, loc=2, bbox_to_anchor=(1.01, 1.)) plot_tracker.sub_plot_obj.set_title('True vs Predicted') plot_tracker.sub_plot_obj.set_ylabel('y') elif metric_id == constants.DATA_POINTS: plot_tracker.data['buffer_size'] = 100 plot_tracker.data['X'] = FastBuffer( plot_tracker.data['buffer_size']) plot_tracker.data['target_values'] = None plot_tracker.data['predictions'] = FastBuffer( plot_tracker.data['buffer_size']) plot_tracker.data['clusters'] = [] plot_tracker.data['clusters_initialized'] = False elif metric_id == constants.RUNNING_TIME: # Only the current time measurement must be saved for data_id in data_ids: plot_tracker.data[data_id] = [ 0.0 for _ in range(self.n_models) ] # To make the annotations memory_time.update(plot_tracker.data) elif metric_id == constants.MODEL_SIZE: plot_tracker.data['model_size'] = [ 0.0 for _ in range(self.n_models) ] memory_time['model_size'] = plot_tracker.data['model_size'] else: # Default case, 'mean' and 'current' performance handle = [] sorted_data_ids = data_ids.copy() sorted_data_ids.sort( ) # For better usage of the color cycle, start with 'current' data for data_id in sorted_data_ids: plot_tracker.data[data_id] = [[] for _ in range(self.n_models) ] plot_tracker.line_objs[data_id] = [ None for _ in range(self.n_models) ] line_obj = plot_tracker.line_objs[data_id] for i in range(self.n_models): if data_id == constants.CURRENT: label = '{} (current, {} samples)'.format( self.model_names[i], self.n_wait) line_style = '-' else: label = '{} (mean)'.format(self.model_names[i]) line_style = ':' line_obj[i], = plot_tracker.sub_plot_obj.plot( self._sample_ids, plot_tracker.data[data_id][i], label=label, linestyle=line_style) handle.append(line_obj[i]) self._set_fig_legend(handle) if metric_id == constants.ACCURACY: plot_tracker.sub_plot_obj.set_title('Accuracy') plot_tracker.sub_plot_obj.set_ylabel('acc') elif metric_id == constants.KAPPA: plot_tracker.sub_plot_obj.set_title('Kappa') plot_tracker.sub_plot_obj.set_ylabel('kappa') elif metric_id == constants.KAPPA_T: plot_tracker.sub_plot_obj.set_title('Kappa T') plot_tracker.sub_plot_obj.set_ylabel('kappa t') elif metric_id == constants.KAPPA_M: plot_tracker.sub_plot_obj.set_title('Kappa M') plot_tracker.sub_plot_obj.set_ylabel('kappa m') elif metric_id == constants.HAMMING_SCORE: plot_tracker.sub_plot_obj.set_title('Hamming score') plot_tracker.sub_plot_obj.set_ylabel('hamming score') elif metric_id == constants.HAMMING_LOSS: plot_tracker.sub_plot_obj.set_title('Hamming loss') plot_tracker.sub_plot_obj.set_ylabel('hamming loss') elif metric_id == constants.EXACT_MATCH: plot_tracker.sub_plot_obj.set_title('Exact Match') plot_tracker.sub_plot_obj.set_ylabel('exact match') elif metric_id == constants.J_INDEX: plot_tracker.sub_plot_obj.set_title('Jaccard Index') plot_tracker.sub_plot_obj.set_ylabel('j-index') elif metric_id == constants.MSE: plot_tracker.sub_plot_obj.set_title('Mean Squared Error') plot_tracker.sub_plot_obj.set_ylabel('mse') elif metric_id == constants.MAE: plot_tracker.sub_plot_obj.set_title('Mean Absolute Error') plot_tracker.sub_plot_obj.set_ylabel('mae') elif metric_id == constants.AMSE: plot_tracker.sub_plot_obj.set_title( 'Average Mean Squared Error') plot_tracker.sub_plot_obj.set_ylabel('amse') elif metric_id == constants.AMAE: plot_tracker.sub_plot_obj.set_title( 'Average Mean Absolute Error') plot_tracker.sub_plot_obj.set_ylabel('amae') elif metric_id == constants.ARMSE: plot_tracker.sub_plot_obj.set_title( 'Average Root Mean Squared Error') plot_tracker.sub_plot_obj.set_ylabel('armse') elif metric_id == constants.DATA_POINTS: plot_tracker.sub_plot_obj.set_title('') plot_tracker.sub_plot_obj.set_xlabel('Feature x') plot_tracker.sub_plot_obj.set_ylabel('Feature y') else: plot_tracker.sub_plot_obj.set_title('Unknown metric') plot_tracker.sub_plot_obj.set_ylabel('') if constants.DATA_POINTS not in self.metrics: plt.xlabel('Samples') if constants.RUNNING_TIME in self.metrics or \ constants.MODEL_SIZE in self.metrics: self._update_time_and_memory_annotations(memory_time) self.fig.subplots_adjust(hspace=.5) self.fig.tight_layout(rect=[0, .04, 1, 0.98], pad=2.6, w_pad=0.4, h_pad=1.0)
from VLBIana.modules.plotSet import * ################################### #plt.style.use('pubstyle') default_cmap = 'gist_earth' colormap = 'inferno' mpl.rcParams['image.cmap'] = default_cmap cmap = cm.get_cmap(default_cmap) bbox_props = dict(boxstyle="square,pad=0.3", color='k', fill=None, lw=0.5) n = 8 colors = cmap(np.linspace(0, 0.95, n)) asize = 8 mm = ['x', '>', '<', '+', 'd', '*', 'p', 'o', '2'] markers = cycle(mm) mpl.rcParams['axes.prop_cycle'] = cycler(color=colors) def plotHist(data, ax=None, **kwargs): '''Possible keywords and default values: 'plot_norm':False 'color':'k' 'xlabel':'Data' 'ylabel':'Proportion', 'fsize':8 'acoord':(0.6,0.9) ''' args = { 'xlabel': 'Data', 'ylabel': 'Proportion', 'asize': asize,
def define_color_cycler_from_map(n, colormap=None): if colormap is None: colormap = default_color_map return cycler( color=[to_hex(colormap(float(i) / float(n))) for i in range(n)])
def plot_interventions_countries( df_interventions, country_list, *, ax=None, prop_cycle=None, color_cycle=None, color=None, label_func=lambda row: f"{row['country']}: {row['key']}", verbose=False, **kwargs): """ Plots interventions as vertical lines. """ # Input handling if ax is None: fig, ax = plt.subplots() ax.xaxis_date() # correctly setup x axis to be a date. ax.xaxis.freq = "D" if prop_cycle is None: # Define the default property cycle prop_cycle = cycler(linestyle=['-', '--', '-.', ':', ':'], marker=['o', 's', 'v', '+', 'x']) if (color is not None) and (color_cycle is not None): raise ValueError("`color` and `color_cycle` cannot be both specified.") if color is not None: color_cycle = cycler(color=[color]) # Trim the list of interventions to only the relevant ones trimmed_interventions = find_unique_interventions(df_interventions, country_list) # Define the correct color_cycle that will match the order of the trimmed # intervention list if color_cycle is None: color_list = _define_colors_of_interventions(trimmed_interventions, country_list) color_cycle = cycler(color=color_list) # Set the property cycle try: ax.set_prop_cycle(prop_cycle * color_cycle) except Exception as e: print(prop_cycle) print(color_cycle) raise e # Prepare the interventions for plotting trimmed_interventions = enable_time_series_plot(trimmed_interventions, "value") trimmed_interventions.sort_values(by=["key", "country", "date"], inplace=True) ylims = ax.get_ylim() vlines = [] d_dict = {} # Plot the lines for i, row in trimmed_interventions.iterrows(): d = row["date"] try: # offset markers when multiple interventions happen on the same day d_dict[d] += 1 except: d_dict[d] = 0 vlines.extend( ax.plot([d, d], [ylims[0], ylims[1] * (1 - 0.04 * d_dict[d])], label=label_func(row), **kwargs)) # Create custom legend lines legend_lines = [] for inter, props in zip(trimmed_interventions["key"].unique(), prop_cycle): if inter not in intervention_labels: intervention_labels[inter] = inter print(f"WARNING: intervention {inter} does not have a label, " + "consider setting `plot_core.intervention_labels['" + f"{inter}']` for better legends of plots.") legend_lines.append( plt.Line2D([0], [0], color="k", lw=2, marker=props["marker"], label=intervention_labels[inter], ls=props["linestyle"]), ) try: lg = ax.get_legend() lg.set_bbox_to_anchor((1.04, 0.5)) ax.add_artist(lg) except: pass # Add a legend ax.legend(handles=legend_lines, title="Intervention types", bbox_to_anchor=(1.04, 1.0), loc='upper left') return ax, (vlines, legend_lines)
def plot_field_loops( fra: pd.DataFrame, field: str, smoothing: List[int] = [7, 2, 3], maille_active="", start_date="2020-03-09", end_date=last_tuesday(), **kwargs, ): """Plots the day on day delta of a field of 'fra' against Args: fra ([type]): [description] field ([type]): [description] smoothing (list, optional): [description]. Defaults to [7, 2, 3]. maille_active (str, optional): [description]. Defaults to "". start_date (str, optional): [description]. Defaults to "2020-03-09". end_date ([type], optional): [description]. Defaults to last_tuesday(). """ smooth_rol_val = lambda df: rol_val(df, smoothing, **kwargs) fra[field + "_smooth_acceleration"] = smooth_rol_val(fra[field + "_jour_jour"]) fra[field + "_jour_smooth"] = smooth_rol_val(fra[field + "_jour"]) fra[field + "_smooth_acceleration_prop"] = (fra[field + "_smooth_acceleration"] / fra[field + "_jour_mma"]) # fig, axs = plt.subplots(1, 3) fig = plt.figure(constrained_layout=True) gs = fig.add_gridspec(nrows=3, ncols=2, wspace=0.3, hspace=0.35) axs = [] axs.append(fig.add_subplot(gs[0, :])) axs.append(fig.add_subplot(gs[1:, 0])) axs.append(fig.add_subplot(gs[1:, 1])) fig.suptitle(f"Acceleration du nombre de {field} en {maille_active}") fig.set_size_inches(10, 8) colors = [] for c in plt.rcParams["axes.prop_cycle"].by_key()["color"]: colors.append(c) colors.append(c) for ax in axs[:2]: ax.set_prop_cycle(cycler(color=colors)) date_debut = pd.date_range(start=start_date, periods=1, freq="d") date_fin = end_date rolling_val = [1] rolled_fra = rol_val(fra, rolling_val) incr_val = date_debut[0].freq * 7 while date_debut < date_fin: week_label = f'semaine du {date_debut[0].strftime("%d/%m")}' ind_log = (date_debut[0] <= rolled_fra.index) & ( rolled_fra.index <= date_debut[0] + incr_val) # Timeline rolled_fra[ind_log].plot( y=field + "_jour", marker="o", linestyle="", ax=axs[0], label="", markersize=3, ) rolled_fra[ind_log].plot(y=field + "_jour_smooth", ax=axs[0], label=week_label) # Timeline rolled_fra[ind_log].plot( x=field + "_jour_smooth", y=field + "_jour_jour", marker="o", ax=axs[1], label="", markersize=3, linestyle="", ) rolled_fra[ind_log].plot( x=field + "_jour_smooth", y=field + "_smooth_acceleration", marker="+", ax=axs[1], label=week_label, ) # Timeline rolled_fra[ind_log].plot( x=field + "_jour_smooth", y=field + "_smooth_acceleration_prop", marker="+", ax=axs[2], label=week_label, ) date_debut += incr_val for ax in axs: lines = [] for line in ax.get_legend().get_lines(): if line.get_label(): lines.append(line) leg = ax.legend(handles=lines, ncol=4) leg.set_bbox_to_anchor((0.9, -0.2)) first_smooth = smoothing[:1] axs[0].set_ylabel(f"{field} par jour\n(moyenne sur {first_smooth} jours)") axs[0].grid("on") lines = [] axs[1].set_xlabel("{} par jour \n(moyenne sur {} jours)".format( field, first_smooth)) axs[1].set_ylabel("Delta journalier de l'abscisse ($x_t - x_{t-1}$)") axs[1].grid("on") axs[2].yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y:.0%}")) axs[2].grid("on") axs[2].set_ylabel("Delta proportionel journalier\nde l'abscisse") lims = axs[2].get_ylim() if lims[0] < -0.2 or lims[1] > 0.5: axs[2].set_ylim(-0.2, 0.5) axs[0].get_legend().remove() axs[1].get_legend().remove() axis_date_limits( axs[0], min_date=start_date, max_date=datetime.datetime.now().strftime("%Y-%m-%d"), ) return axs
def __configure(self, n_sliding, dataset_name, plots, n_learners): """ __configure This function will verify which subplots it should create. For each one of those, it will initialize all relevant objects to keep track of the plotting points. Basic structures needed to keep track of plot values (for each subplot) are: lists of values and matplot line objects. The __configure function will also initialize each subplot with the correct name and setup the axis. The subplot size will self adjust to each screen size, so that data can be better viewed in different contexts. Parameters ---------- n_sliding: int The number of samples in the sliding window to track recent performance. dataset_name: string (Default: 'Unnamed graph') The title of the plot. Algorithmically it's not important. plots: list A list containing all the subplots to plot. Can be any of: 'accuracy', 'kappa', 'scatter', 'hamming_score', 'hamming_loss', 'exact_match', 'j_index', 'mean_square_error', 'mean_absolute_error', 'true_vs_predicted', 'kappa_t', 'kappa_m' n_learners: int The number of learners to compare. """ data_points = False font_size_small = 8 font_size_medium = 10 font_size_large = 12 plt.rc('font', size=font_size_small) # controls default text sizes plt.rc('axes', titlesize=font_size_medium) # font size of the axes title plt.rc('axes', labelsize=font_size_small) # font size of the x and y labels plt.rc('xtick', labelsize=font_size_small) # font size of the tick labels plt.rc('ytick', labelsize=font_size_small) # font size of the tick labels plt.rc('legend', fontsize=font_size_small) # legend font size plt.rc('figure', titlesize=font_size_large) # font size of the figure title warnings.filterwarnings("ignore", ".*GUI is implemented.*") warnings.filterwarnings("ignore", ".*left==right.*") warnings.filterwarnings("ignore", ".*Passing 1d.*") self.n_sliding = n_sliding self.dataset_name = dataset_name self.plots = plots self.n_learners = n_learners self.sample_id = [] plt.ion() self.fig = plt.figure(figsize=(9, 5)) self.fig.suptitle(dataset_name) self.num_plots = len(self.plots) base = 11 + self.num_plots * 100 # 3-digit integer describing the position of the subplot. self.fig.canvas.set_window_title('scikit-multiflow') if constants.ACCURACY in self.plots: self.current_accuracy = [[] for _ in range(self.n_learners)] self.mean_accuracy = [[] for _ in range(self.n_learners)] self.subplot_accuracy = self.fig.add_subplot(base) self.subplot_accuracy.set_title('Accuracy') self.subplot_accuracy.set_ylabel('Accuracy') base += 1 self.line_current_accuracy = [None for _ in range(self.n_learners)] self.line_mean_accuracy = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_current_accuracy[i], = self.subplot_accuracy.plot( self.sample_id, self.current_accuracy[i], label='{} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_accuracy[i], = self.subplot_accuracy.plot( self.sample_id, self.mean_accuracy[i], label='{} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_accuracy[i]) handle.append(self.line_mean_accuracy[i]) self._set_fig_legend(handle) self.subplot_accuracy.set_ylim(0, 1) if constants.KAPPA in self.plots: self.current_kappa = [[] for _ in range(self.n_learners)] self.mean_kappa = [[] for _ in range(self.n_learners)] self.subplot_kappa = self.fig.add_subplot(base) self.subplot_kappa.set_title('Kappa') self.subplot_kappa.set_ylabel('Kappa') base += 1 self.line_current_kappa = [None for _ in range(self.n_learners)] self.line_mean_kappa = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_current_kappa[i], = self.subplot_kappa.plot( self.sample_id, self.current_kappa[i], label='Model {} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_kappa[i], = self.subplot_kappa.plot( self.sample_id, self.mean_kappa[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_kappa[i]) handle.append(self.line_mean_kappa[i]) self._set_fig_legend(handle) self.subplot_kappa.set_ylim(-1, 1) if constants.KAPPA_T in self.plots: self.current_kappa_t = [[] for _ in range(self.n_learners)] self.mean_kappa_t = [[] for _ in range(self.n_learners)] self.subplot_kappa_t = self.fig.add_subplot(base) self.subplot_kappa_t.set_title('Kappa T') self.subplot_kappa_t.set_ylabel('Kappa T') base += 1 self.line_current_kappa_t = [None for _ in range(self.n_learners)] self.line_mean_kappa_t = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_current_kappa_t[i], = self.subplot_kappa_t.plot( self.sample_id, self.current_kappa_t[i], label='Model {} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_kappa_t[i], = self.subplot_kappa_t.plot( self.sample_id, self.mean_kappa_t[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_kappa_t[i]) handle.append(self.line_mean_kappa_t[i]) self._set_fig_legend(handle) self.subplot_kappa_t.set_ylim(-1, 1) if constants.KAPPA_M in self.plots: self.current_kappa_m = [[] for _ in range(self.n_learners)] self.mean_kappa_m = [[] for _ in range(self.n_learners)] self.subplot_kappa_m = self.fig.add_subplot(base) self.subplot_kappa_m.set_title('Kappa M') self.subplot_kappa_m.set_ylabel('Kappa M') base += 1 self.line_current_kappa_m = [None for _ in range(self.n_learners)] self.line_mean_kappa_m = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_current_kappa_m[i], = self.subplot_kappa_m.plot( self.sample_id, self.current_kappa_m[i], label='Model {} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_kappa_m[i], = self.subplot_kappa_m.plot( self.sample_id, self.mean_kappa_m[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_kappa_m[i]) handle.append(self.line_mean_kappa_m[i]) self._set_fig_legend(handle) self.subplot_kappa_m.set_ylim(-1, 1) if constants.HAMMING_SCORE in self.plots: self.mean_hamming_score = [[] for _ in range(self.n_learners)] self.current_hamming_score = [[] for _ in range(self.n_learners)] self.subplot_hamming_score = self.fig.add_subplot(base) self.subplot_hamming_score.set_title('Hamming score') self.subplot_hamming_score.set_ylabel('Hamming score') base += 1 self.line_current_hamming_score = [ None for _ in range(self.n_learners) ] self.line_mean_hamming_score = [ None for _ in range(self.n_learners) ] handle = [] for i in range(self.n_learners): self.line_current_hamming_score[ i], = self.subplot_hamming_score.plot( self.sample_id, self.current_hamming_score[i], label='Model {} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_hamming_score[ i], = self.subplot_hamming_score.plot( self.sample_id, self.mean_hamming_score[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_hamming_score[i]) handle.append(self.line_mean_hamming_score[i]) self._set_fig_legend(handle) self.subplot_hamming_score.set_ylim(0, 1) if constants.HAMMING_LOSS in self.plots: self.mean_hamming_loss = [[] for _ in range(self.n_learners)] self.current_hamming_loss = [[] for _ in range(self.n_learners)] self.subplot_hamming_loss = self.fig.add_subplot(base) self.subplot_hamming_loss.set_title('Hamming loss') self.subplot_hamming_loss.set_ylabel('Hamming loss') base += 1 self.line_current_hamming_loss = [ None for _ in range(self.n_learners) ] self.line_mean_hamming_loss = [ None for _ in range(self.n_learners) ] handle = [] for i in range(self.n_learners): self.line_current_hamming_loss[ i], = self.subplot_hamming_loss.plot( self.sample_id, self.current_hamming_loss[i], label='Model {} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_hamming_loss[ i], = self.subplot_hamming_loss.plot( self.sample_id, self.mean_hamming_loss[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_hamming_loss[i]) handle.append(self.line_mean_hamming_loss[i]) self._set_fig_legend(handle) self.subplot_hamming_loss.set_ylim(0, 1) if constants.EXACT_MATCH in self.plots: self.mean_exact_match = [[] for _ in range(self.n_learners)] self.current_exact_match = [[] for _ in range(self.n_learners)] self.subplot_exact_match = self.fig.add_subplot(base) self.subplot_exact_match.set_title('Exact matches') self.subplot_exact_match.set_ylabel('Exact matches') base += 1 self.line_current_exact_match = [ None for _ in range(self.n_learners) ] self.line_mean_exact_match = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_current_exact_match[ i], = self.subplot_exact_match.plot( self.sample_id, self.current_exact_match[i], label='Model {} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_exact_match[i], = self.subplot_exact_match.plot( self.sample_id, self.mean_exact_match[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_exact_match[i]) handle.append(self.line_mean_exact_match[i]) self._set_fig_legend(handle) self.subplot_exact_match.set_ylim(0, 1) if constants.J_INDEX in self.plots: self.mean_j_index = [[] for _ in range(self.n_learners)] self.current_j_index = [[] for _ in range(self.n_learners)] self.subplot_j_index = self.fig.add_subplot(base) self.subplot_j_index.set_title('Jaccard index') self.subplot_j_index.set_ylabel('Jaccard index') base += 1 self.line_current_j_index = [None for _ in range(self.n_learners)] self.line_mean_j_index = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_current_j_index[i], = self.subplot_j_index.plot( self.sample_id, self.current_j_index[i], label='Model {} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_j_index[i], = self.subplot_j_index.plot( self.sample_id, self.mean_j_index[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_j_index[i]) handle.append(self.line_mean_j_index[i]) self._set_fig_legend(handle) self.subplot_j_index.set_ylim(0, 1) if constants.MSE in self.plots: self.mean_mse = [[] for _ in range(self.n_learners)] self.current_mse = [[] for _ in range(self.n_learners)] self.subplot_mse = self.fig.add_subplot(base) self.subplot_mse.set_title('Mean Squared Error') self.subplot_mse.set_ylabel('MSE') base += 1 self.line_current_mse = [None for _ in range(self.n_learners)] self.line_mean_mse = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_current_mse[i], = self.subplot_mse.plot( self.sample_id, self.current_mse[i], label='Model {} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_mse[i], = self.subplot_mse.plot( self.sample_id, self.mean_mse[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_mse[i]) handle.append(self.line_mean_mse[i]) self._set_fig_legend(handle) self.subplot_mse.set_ylim(0, 1) if constants.MAE in self.plots: self.mean_mae = [[] for _ in range(self.n_learners)] self.current_mae = [[] for _ in range(self.n_learners)] self.subplot_mae = self.fig.add_subplot(base) self.subplot_mae.set_title('Mean Absolute Error') self.subplot_mae.set_ylabel('MAE') base += 1 self.line_current_mae = [None for _ in range(self.n_learners)] self.line_mean_mae = [None for _ in range(self.n_learners)] handle = [] for i in range(self.n_learners): self.line_current_mae[i], = self.subplot_mae.plot( self.sample_id, self.current_mae[i], label='Model {} (sliding {} samples)'.format( self.model_names[i], self.n_sliding)) self.line_mean_mae[i], = self.subplot_mae.plot( self.sample_id, self.mean_mae[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_current_mae[i]) handle.append(self.line_mean_mae[i]) self._set_fig_legend(handle) self.subplot_mae.set_ylim(0, 1) if constants.TRUE_VS_PREDICTED in self.plots: self.true_values = [] self.pred_values = [[] for _ in range(self.n_learners)] self.subplot_true_vs_predicted = self.fig.add_subplot(base) self.subplot_true_vs_predicted.set_title('True vs Predicted') self.subplot_true_vs_predicted.set_ylabel('y') self.subplot_true_vs_predicted.set_prop_cycle( cycler('color', ['c', 'm', 'y', 'k'])) base += 1 if self.task_type == constants.CLASSIFICATION: self.line_true, = self.subplot_true_vs_predicted.step( self.sample_id, self.true_values, label='True value') else: self.line_true, = self.subplot_true_vs_predicted.plot( self.sample_id, self.true_values, label='True value') handle = [self.line_true] self.line_pred = [None for _ in range(self.n_learners)] for i in range(self.n_learners): if self.task_type == constants.CLASSIFICATION: self.line_pred[i], = self.subplot_true_vs_predicted.step( self.sample_id, self.pred_values[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') else: self.line_pred[i], = self.subplot_true_vs_predicted.plot( self.sample_id, self.pred_values[i], label='Model {} (global)'.format(self.model_names[i]), linestyle='dotted') handle.append(self.line_pred[i]) self.subplot_true_vs_predicted.legend(handles=handle) self.subplot_true_vs_predicted.set_ylim(0, 1) if constants.DATA_POINTS in self.plots: data_points = True self.Flag = True self.X = FastBuffer(5000) self.targets = [] self.prediction = [] self.clusters = [] self.subplot_scatter_points = self.fig.add_subplot(base) base += 1 if data_points: plt.xlabel('X1') else: plt.xlabel('Samples') self.fig.subplots_adjust(hspace=.5) self.fig.tight_layout(rect=[0, .04, 1, 0.98], pad=2.6, w_pad=0.5, h_pad=1.0)
dark2_colors = [(0.10588235294117647, 0.6196078431372549, 0.4666666666666667), (0.8509803921568627, 0.37254901960784315, 0.00784313725490196), (0.4588235294117647, 0.4392156862745098, 0.7019607843137254), (0.9058823529411765, 0.1607843137254902, 0.5411764705882353), (0.4, 0.6509803921568628, 0.11764705882352941), (0.9019607843137255, 0.6705882352941176, 0.00784313725490196), (0.6509803921568628, 0.4627450980392157, 0.11372549019607843)] from matplotlib.rcsetup import cycler mpl.rc('figure', figsize=(10,6), dpi=150) mpl.rc('axes', facecolor='white', labelsize='medium', prop_cycle=cycler('color', dark2_colors )) mpl.rc('lines', lw=2) mpl.rc('patch', ec='white', fc=dark2_colors[0]) mpl.rc('font', size=14, family='StixGeneral') def remove_border(axes=None, top=False, right=False, left=True, bottom=True): """ Minimize chartjunk by stripping out unnecesasry plot borders and axis ticks The top/right/left/bottom keywords toggle whether the corresponding plot border is drawn """ ax = axes or plt.gca() ax.spines['top'].set_visible(top) ax.spines['right'].set_visible(right) ax.spines['left'].set_visible(left)
import brewer2mpl import matplotlib as mpl import matplotlib.image as image import matplotlib.pyplot as plt from matplotlib.rcsetup import cycler # look at the map @http://colorbrewer2.org, pick a set and map to a variable gmap = brewer2mpl.get_map('YlOrRd', 'Sequential', 7, reverse=True).hex_colors mpl.rcParams['figure.figsize'] = (10, 6) mpl.rcParams['figure.dpi'] = 150 mpl.rcParams['axes.prop_cycle'] = cycler('color', gmap) mpl.rcParams['lines.linewidth'] = 2 mpl.rcParams['axes.facecolor'] = 'white' mpl.rcParams['font.size'] = 14 mpl.rcParams['patch.edgecolor'] = 'white' mpl.rcParams['patch.facecolor'] = gmap[0] mpl.rcParams['font.family'] = 'StixGeneral' mpl.rcParams['axes.titlepad'] = 10 mpl.rcParams['figure.constrained_layout.use'] = True def datalab_default( axes=None, show_axes=(True, False, True, False), grid=None, xlim=None, ylim=None, title=None, xlabel=None, ylabel=None,