def draw_heat_ok(self, fig, ax, scale: str): self.df_ok = self.df_scaled['ok'].copy() # draw color_list = ["green", "olive", "darkkhaki", "orange", "red"][::-1] heatmap = ax.pcolor( self.df_ok.T, # cm.get_cmap('viridis', 256)) cmap=LinearSegmentedColormap.from_list("", color_list), vmin=np.nanmin(self.df_ok.T), vmax=np.nanmax(self.df_ok.T), edgecolors='k', linewidth=1) # ax.patch.set(color='red') # hatch='x',edgecolor='red',fill=True, # fig.colorbar(heatmap, extend='both') # # set x axis ax.xaxis.set_major_locator( ticker.IndexLocator(self.scales[scale]['x_base'], 0.0)) # 0.5 format_str = self.scales[scale]['format'] ax.xaxis.set_major_formatter( ticker.FuncFormatter( lambda x, pos: f"{self.df_ok.index[np.clip(int(x), 0, len(self.df_ok.index) - 1)].strftime(format_str)}" )) ax.tick_params(axis='x', labelrotation=90.) ax.set_xlabel(self.scales[scale]['units']) # set y axis (host_names ordered by host_info[seqn] ax.yaxis.set_major_locator(ticker.IndexLocator(1.0, 0.5)) yformatter = lambda x, pos: f"{self.df_ok.columns[int(x)] if x < len(self.df_ok.columns) else '=No label='}" ax.yaxis.set_major_formatter(ticker.FuncFormatter(yformatter))
def ttp_style( ax, df_, padding=0, rotate_xticks=True, ): #place and null major ticks (we still need them for the grid) ax.xaxis.set_major_locator(ticker.LinearLocator(len(df_.index) + 1)) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.yaxis.set_major_locator(ticker.LinearLocator(len(df_.columns) + 1)) ax.yaxis.set_major_formatter(ticker.NullFormatter()) #place and format minor ticks (used to substitute for centered major tick labels) ax.xaxis.set_minor_locator(ticker.IndexLocator(1, 0.5)) ax.xaxis.set_minor_formatter(ticker.FixedFormatter(df_.index)) ax.yaxis.set_minor_locator(ticker.IndexLocator(1, 0.5)) ax.yaxis.set_minor_formatter(ticker.FixedFormatter(df_.columns)) #remove bottom and top small tick lines plt.tick_params(axis='x', which='both', bottom='off', top='off', left='off', right='off') plt.tick_params(axis='y', which='both', bottom='off', top='off', left='off', right='off') #Set only 7th minor tick label to visible for label in ax.xaxis.get_minorticklabels(): label.set_visible(False) for label in ax.xaxis.get_minorticklabels()[padding::7]: label.set_visible(True) for label in ax.yaxis.get_minorticklabels(): label.set_visible(False) for label in ax.yaxis.get_minorticklabels(): label.set_visible(True) #Rotate xticks if rotate_xticks: plt.setp(ax.xaxis.get_minorticklabels(), rotation=90) # create grid ax.xaxis.grid(True, which='major', color='1', linestyle='-') ax.yaxis.grid(True, which='major', color='1', linestyle='-') #delete all spines for spine in ["right", "left", "top", "bottom"]: ax.spines[spine].set_visible(False) return ax
def plot(data, columnNames=None, timeColumnName=None, majorLocatorStep=20, majorOffset=0, minorLocatorStep=5, minorOffset=0, displayMinor=False, timeFormat='%Y-%m-%d', rotation=45, stickWidth=0.6, alpha=1): ''' 根据所给的数据,画出蜡烛图 @param: data: 原始数据,要求为pandas.DataFrame的形式,默认的有open, close, high low这四列,反之需要通过columnNames参数提供,依次的顺序为openName, closeName, highName, lowName,若要画出时间轴,则需要数据中有date列, 否则则需要通过使用的时候通过timeFormat来提供 columnNames: 默认data中有open, close, high, low这些列,反之则需要自行提供 timeColumnName: 当需要画以时间为横轴的图时,需要提供时间列的列名 majorLocatorStep: 主刻度间隔,默认为间隔20个数据 minorLocatorStep: 副刻度间隔,默认为间隔5个数据 displayMinor: 是否在副刻度上也标明时间或者顺序下标,默认不标明 majorFormat: 解析时间列主刻度的方法,需按照datetime中的形式解析,默认为%Y-%m-%d minorFormat: 解析时间列副刻度的方法,需按照datetime中的形式解析,默认为%Y-%m-%d rotation: 横轴值旋转度数,默认旋转45度 stickWidth: 蜡烛图的宽度,默认为0.6 alpha: 蜡烛图颜色的深度,默认为1 ''' plt.style.use('seaborn-ticks') fig, ax = plt.subplots() if not columnNames is None: openName, closeNames, highName, lowName = columnNames else: openName, closeNames, highName, lowName = ('open', 'close', 'high', 'low') opens, closes, highs, lows = data[openName].tolist(), data[closeNames].tolist(), data[ highName].tolist(), data[lowName].tolist() fig.subplots_adjust(bottom=0.2) majorLocator = ticker.IndexLocator(majorLocatorStep, majorOffset) ax.xaxis.set_major_locator(majorLocator) minorLocator = ticker.IndexLocator(minorLocatorStep, minorOffset) ax.xaxis.set_minor_locator(minorLocator) if not timeColumnName is None: times = data[timeColumnName].tolist() time_formatterSetting(ax, times, majorLocatorStep, majorOffset, timeFormat, displayMinor, minorLocatorStep, minorOffset) finance.candlestick2_ohlc(ax, opens, highs, lows, closes, width=stickWidth, colorup='r', colordown='g', alpha=alpha) plt.setp(ax.get_xticklabels(), rotation=rotation) if displayMinor: plt.setp(ax.xaxis.get_minorticklabels(), rotation=rotation) xmin, xmax = plt.xlim() plt.xlim(xmin=xmin-1) plt.grid(True) plt.show()
def plota(fig): fig.figimage(bgimg) ax = fig.add_subplot(111) ax.plot(X, Y1, c=(0.25, 0.25, 1.00), lw=2, label="Blue signal", zorder=10) ax.plot(X, Y2, c=(1.00, 0.25, 0.25), lw=2, label="Red signal") ax.plot(X, Y3, linewidth=0, marker='o', markerfacecolor='w', markeredgecolor='k') ax.set_facecolor('None') ax.xaxis.set_major_locator(ticker.IndexLocator(0.4, -0.1)) ax.xaxis.set_minor_locator(ticker.IndexLocator(0.2, -0.1)) return ax
def apply_to_axis(self, axis, **kwargs): """Set the tick positions and labels on an axis using this formatter. :param axis: the matplotlib.axis object this formatter will be applied to, :param kwargs: Any remaining keyword arguments will be forwarded to the matplotlib.text.Text objects making up the major labels, so they can be formatted. :return: None """ # set the minor ticks, one at each simulated k-vector: axis.set_minor_locator(mticker.IndexLocator(1, 0)) # set the tick positions: axis.set_ticks(self._ticks) # set the tick label strings and label formatting: axis.set_ticklabels(self._labels, **kwargs) # The formatter in set_major_formatter provides the data that is shown # in the status bar of the plot while the mouse is moving in the plot: # (This overrides the label strings set in xaxis.set_ticklabels, # but set_ticklabels is still necessary to set the formatting; # Also, set_ticklabels must be called before, because set_ticklabels # overrides the major_formatter.) axis.set_major_formatter(self) # set the axis label: axis.set_label_text(self._axis_label, size='x-large')
def plot_first_time_guests_line(x, y): style.use('ggplot') fig = plt.figure(figsize=(15, 8)) ax = fig.add_subplot(111) ax.plot(x, y, label=f'{FIRST_TIME_GUESTS_CATEGORY}', marker='o', color='teal') ax.xaxis.set_major_locator(ticker.IndexLocator(7, 0)) ax.xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%y')) ax.set_ylim(bottom=0) plt.title(f'{FIRST_TIME_GUESTS_CATEGORY}') plt.xlabel('Week') plt.ylabel(f'{FIRST_TIME_GUESTS_CATEGORY}') # file_name = f'{column}_{workbook_category}_line.png' # full_path = get_file_path(workbook_category, file_name) # plt.savefig(full_path, bbox_inches='tight') # plt.close(fig) plt.legend() plt.show()
def plot_activation(matrix, step, save_to=None): save_to = os.path.join(".", "activations") if save_to is None else save_to os.makedirs(save_to, exist_ok=True) if len(matrix.shape) != 2: raise ValueError('Input "matrix" should have 2 rank, but it is', str(len(matrix.shape))) num_label = matrix.shape[1] - 1 matrix = matrix[matrix[:, num_label].argsort()] fig, axes = plt.subplots(ncols=1, nrows=num_label, figsize=(15, 12)) fig.suptitle("The probability of entity presence (step %s)" % str(step), fontsize=20) fig.tight_layout() for i, ax in enumerate(axes.flatten()): idx = num_label - (i + 1) ax.spines['top'].set_color('none') ax.spines['bottom'].set_color('none') ax.set_ylim(0, 1.05) ax.set_ylabel("Capsule " + str(idx)) ax.yaxis.set_major_locator(ticker.NullLocator()) if idx > 0: ax.xaxis.set_major_locator(ticker.NullLocator()) else: ax.xaxis.set_major_locator(ticker.IndexLocator(base=500, offset=0)) ax.set_xlabel("Sample index ") ax.plot(matrix[:, idx]) ax_prime = ax.twinx() ax_prime.spines['top'].set_color('none') ax_prime.spines['bottom'].set_color('none') plt.subplots_adjust(hspace=0.2, left=0.05, right=0.95, bottom=0.05, top=.95) plt.savefig(os.path.join(save_to, "activation_%s.png" % str(step))) plt.close()
def set_axis_yearweek_weekdayhour(ax, s): #plt.xlim(0, len(s)) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.xaxis.set_major_locator(ticker.IndexLocator(base=24, offset=0)) ax.xaxis.set_minor_formatter(ticker.FuncFormatter(weekdayhour_formatter)) ax.xaxis.set_minor_locator(ticker.IndexLocator(base=24, offset=12)) for tick in ax.xaxis.get_minor_ticks(): tick.tick1line.set_markersize(0) tick.tick2line.set_markersize(0) tick.label1.set_verticalalignment('center') ax.yaxis.set_major_formatter( ticker.FuncFormatter(yearweek_formatter(s, 13))) ax.yaxis.set_major_locator(ticker.MultipleLocator(13))
def _ticker(self): ''' Return two sequences: ticks (colorbar data locations) and ticklabels (strings). ''' locator = self.locator formatter = self.formatter if locator is None: if self.boundaries is None: if isinstance(self.norm, colors.no_norm): nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=0) else: locator = ticker.MaxNLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.no_norm): intv = Interval(Value(self._values[0]), Value(self._values[-1])) else: intv = Interval(Value(self.vmin), Value(self.vmax)) locator.set_view_interval(intv) locator.set_data_interval(intv) formatter.set_view_interval(intv) formatter.set_data_interval(intv) b = nx.array(locator()) eps = 0.001 * (self.vmax - self.vmin) b = nx.compress((b >= self.vmin - eps) & (b <= self.vmax + eps), b) ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t) for t in b] offset_string = formatter.get_offset() return ticks, ticklabels, offset_string
def showGridNet(myax, mycrs): interval_lat = 10 interval_lon = 10 gl = myax.gridlines(crs=mycrs, draw_labels=False, linewidth=2, color='red', alpha=0.5, linestyle='-') gl.xlabels_top = False gl.ylabels_left = False #gl.xlines = False #gl.xlocator = mticker.FixedLocator([-180, -45, 0, 45, 180]) gl.xlocator = mticker.IndexLocator(interval_lon, -180) gl.ylocator = mticker.IndexLocator(interval_lat, -90)
def draw_gnomes(ax, X_gnomes, num_bins, num_grids=1, fontsize=16, colors=None, annot=None): if annot is None: annot = np.empty(shape=X_gnomes.shape, dtype=np.object) for i in range(num_bins): for j in range(num_bins): annot[i, j] = "%d,%d" % (i, j) if colors is None: colors_pal = sns.color_palette("deep", n_colors=num_grids) # colors for the heatmap representation colors = [np.array(colorConverter.to_rgba("white"))] for k in range(num_grids): curr_color = np.array(colorConverter.to_rgba(colors_pal[k])) colors.append(curr_color) gnome_plot = sns.heatmap(X_gnomes, ax=ax, square=True, linewidths=0.05, linecolor='k', cbar=False, cmap=colors, annot=annot, fmt='', annot_kws={ 'fontsize': fontsize, 'color': 'k', 'alpha': 0.4 }, clip_on=False) # X-Axis bin labels gnome_plot.set_xticklabels([]) gnome_plot.xaxis.set_major_locator( ticker.IndexLocator(num_bins, num_bins / 2)) # gnome_plot.set_xticklabels([k for k in range(num_bins)], fontdict={'fontsize': 12}) # Y-Axis hypergrid angle labels gnome_plot.yaxis.set_major_locator( ticker.IndexLocator(num_bins, num_bins / 2)) gnome_plot.set_yticklabels([]) gnome_plot.set_aspect('equal')
def _ticker(self): ''' Return the sequence of ticks (colorbar data locations), ticklabels (strings), and the corresponding offset string. ''' locator = self.locator formatter = self.formatter if locator is None: if self.boundaries is None: if isinstance(self.norm, colors.NoNorm): nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=0) elif isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries locator = ticker.FixedLocator(b, nbins=10) elif isinstance(self.norm, colors.LogNorm): locator = ticker.LogLocator(subs='all') elif isinstance(self.norm, colors.SymLogNorm): # The subs setting here should be replaced # by logic in the locator. locator = ticker.SymmetricalLogLocator( subs=np.arange(1, 10), linthresh=self.norm.linthresh, base=10) else: if mpl.rcParams['_internal.classic_mode']: locator = ticker.MaxNLocator() else: locator = ticker.AutoLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.NoNorm) and self.boundaries is None: intv = self._values[0], self._values[-1] else: intv = self.vmin, self.vmax locator.create_dummy_axis(minpos=intv[0]) formatter.create_dummy_axis(minpos=intv[0]) locator.set_view_interval(*intv) locator.set_data_interval(*intv) formatter.set_view_interval(*intv) formatter.set_data_interval(*intv) b = np.array(locator()) if isinstance(locator, ticker.LogLocator): eps = 1e-10 b = b[(b <= intv[1] * (1 + eps)) & (b >= intv[0] * (1 - eps))] else: eps = (intv[1] - intv[0]) * 1e-10 b = b[(b <= intv[1] + eps) & (b >= intv[0] - eps)] self._tick_data_values = b ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t, i) for i, t in enumerate(b)] offset_string = formatter.get_offset() return ticks, ticklabels, offset_string
def plottrialstats(ax,data,label=None,offset=0,scale=1): mean = data[:,0] std = data[:,1] ax.xaxis.set_major_locator(ticker.IndexLocator(1,0)) x = (np.arange(len(data))*scale)+offset (_,caps,_) = plt.errorbar(x,mean,std,fmt=None,label=label,zorder=100,capthick=1,alpha=0.4) for cap in caps: cap.remove() plt.xlim(-0.5-offset/2,(len(data)*scale)-0.5)
def final_confmat(self): font = FontProperties() font.set_family(['Times New Roman', 'serif']) font.set_size(9) # TIPO = 'LOGREG' # conf_mat = np.array([[8,4], [0,37]]) # conf_mat = np.array([[4,8],[0,37]]) #DT # conf_mat = np.array([[8,4],[0,37]]) #RF+PCA+OS # conf_mat = np.array([[7,5],[0,37]]) #SVM+PCA5+OS # conf_mat = np.array([[10,2],[1,36]]) #LOGREG conf_mat = np.array([[2, 0], [0, 6]]) # conf_mat = np.array() # conf_mat = np.array() # conf_mat = np.array() # conf_mat = np.array() fig, ax = plt.subplots(nrows=1, ncols=1) im = ax.imshow(conf_mat, interpolation='nearest', cmap=plt.cm.GnBu) # ax.figure.colorbar(im, ax=ax) ax.set(yticks=[0, 1], xticks=[0, 1], yticklabels=['Healthy', 'PD'], xticklabels=['Healthy', 'PD']) ax.yaxis.set_major_locator(ticker.IndexLocator(base=1, offset=0.5)) for i in range(2): for j in range(2): text = ax.text(j, i, conf_mat[i, j], ha="center", va="center", color="#00000090", fontweight='bold', fontproperties=font, fontsize=16) ax.set_xlabel('Predicted class', labelpad=14, fontsize='14', fontproperties=font) ax.set_ylabel('True class', labelpad=14, rotation=90, fontsize='14', fontproperties=font) plt.show() return
def test_set_params(self): """ Create index locator with 3 base, 4 offset. and change it to something else. See if change was successful. Should not exception. """ index = mticker.IndexLocator(base=3, offset=4) index.set_params(base=7, offset=7) assert index._base == 7 assert index.offset == 7
def test_IndexLocator_set_params(): """ Create index locator with 3 base, 4 offset. and change it to something else. See if change was successful. Should not exception. """ index = mticker.IndexLocator(base=3, offset=4) index.set_params(base=7, offset=7) nose.tools.assert_equal(index._base, 7) nose.tools.assert_equal(index.offset, 7)
def display_conf_matrix(conf_mat, display=False, save=False, path=None): n_classes = len(conf_mat) ticks = [i - 0.5 for i in range(n_classes)] fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 8)) im = ax.imshow(conf_mat, interpolation='nearest', cmap=plt.cm.jet) tick_strings = [] for i in range(n_classes): if (i + 1) % 10 == 0: tick_strings.append(str(i + 1)) else: tick_strings.append('') ax.set(yticks=ticks, xticks=ticks, yticklabels=tick_strings, xticklabels=tick_strings) ax.yaxis.set_major_locator(ticker.IndexLocator(base=1, offset=0.5)) ax.xaxis.set_major_locator(ticker.IndexLocator(base=1, offset=0.5)) ax.tick_params(length=0, labelsize='14') ax.set_xlabel('Predicted class', labelpad=14, fontsize='16') ax.set_ylabel('True class', labelpad=14, rotation=90, fontsize='16') if display: plt.show() plt.close() # Save figures if save: if path == None: raise RuntimeError( "Devi passare il path alla funzione display_conf_matrix") fig.savefig(path + '/conf_matrix.png') return
def axisinfo(unit, axis): 'return the Foo AxisInfo' if unit == 1.0 or unit == 2.0: return units.AxisInfo( majloc=ticker.IndexLocator(4, 0), majfmt=ticker.FormatStrFormatter("VAL: %s"), label='foo', ) else: return None
def plot_epoch_average(data,label=None,offset=0,scale=1): mean = [np.mean(epoch) for epoch in data] std = [np.std(epoch) for i,epoch in enumerate(data)] ax = plt.gca() ax.xaxis.set_major_locator(ticker.IndexLocator(1,0)) #c = next(ax._get_lines.color_cycle) x = (np.arange(len(data))*scale)+offset #plt.plot(x,mean,'--',zorder=0,color=c) (_,caps,_) = plt.errorbar(x,mean,std,fmt=None,label=label,zorder=100,capthick=1,alpha=0.4) for cap in caps: cap.remove() plt.xlim(-0.5-offset/2,(len(data)*scale)-0.5)
def plot_heatmap(sel): fig = plt.figure() ax = fig.add_subplot(111) plt.pcolor(sel) xs = range(sel.shape[1]) ys = range(sel.shape[0]) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.xaxis.set_major_locator(ticker.IndexLocator(base=24, offset=0)) ax.xaxis.set_minor_formatter(FuncFormatter(weekday_hour_formatter)) ax.xaxis.set_minor_locator(ticker.IndexLocator(base=24, offset=12)) for tick in ax.xaxis.get_minor_ticks(): tick.tick1line.set_markersize(0) tick.tick2line.set_markersize(0) tick.label1.set_verticalalignment('center') ax.yaxis.set_major_formatter(FuncFormatter(yearweek_formatter(sel, 13))) ax.yaxis.set_major_locator(MultipleLocator(13))
def firstFrame(): global fig, ax, hPlot fig, ax = plt.subplots() ax.set_title("H") hh = H[:, 0:ncol] loc = tkr.IndexLocator(base=1, offset=1) ax.xaxis.set_major_locator(loc) ax.yaxis.set_major_locator(loc) grid = ax.grid(which='major', axis='both', linestyle='-') hPlot = ax.imshow(hh, interpolation='nearest', clim=(-0.5, 0.5)) plotArrows() plt.show(block=False)
def plot_standard_curves(df, NMETA, filename): df_ = df.iloc[:, NMETA:].transpose().copy() cts = compute_cts(df_, thresh=0.01) df_ampl_temp = df.copy() df_ampl_temp['CT'] = cts.values encod = LabelEncoder() df_ampl_temp['Target_enc'] = encod.fit_transform(df_ampl_temp['Target']) df_ampl_temp_av = df_ampl_temp.groupby(['Target', 'Conc']).mean().reset_index() df_ampl_temp_av['Conc.'] = df_ampl_temp_av['Conc'].apply( lambda x: f'1E{int(np.log10(x))}') fig, ax = plt.subplots(1, 1, figsize=(10, 3.5), dpi=300, constrained_layout=True) sns.scatterplot(ax=ax, x='Target_enc', y='CT', data=df_ampl_temp_av, style='Conc.', s=150, zorder=100, hue='Target_enc', palette=[f'C{i}' for i in range(9)]) ax.set_xlim((-1, 9.3)) ax.set_xticks(np.arange(9)) ax.set_xticklabels(encod.classes_) ax.set_xlabel('') ax.set_ylabel('') ax.set_ylim((0, 40)) ax.set_yticks(np.arange(0, 40, step=5)) ax.grid(alpha=0.5, axis='y', linestyle='--') ax.grid(which='minor', axis='x') handles, labels = ax.get_legend_handles_labels() ax.legend(handles[-9:], labels[-9:], loc='center right') ax.xaxis.set_minor_locator(ticker.IndexLocator(offset=-0.5, base=1)) ax.set_xticks([]) plt.savefig(filename) plt.show()
def show_slices(slices, shape, show=False): """Function that shows what points are selected by a particular slice operation""" import pylab as pl from matplotlib import ticker pl.figure() n_elements_x, n_elements_y, Nx, Ny = shape psi = np.zeros(shape) psi[slices] = 1 psi = psi.transpose(0, 2, 1, 3).reshape( (n_elements_x * Nx, n_elements_y * Ny)) pl.imshow(psi.transpose(), origin='lower', interpolation='nearest', cmap='gray_r') locx = ticker.IndexLocator(base=Nx, offset=0) locy = ticker.IndexLocator(base=Ny, offset=0) ax = pl.gca() ax.xaxis.set_minor_locator(locx) ax.yaxis.set_minor_locator(locy) ax.grid(which='minor', axis='both', linestyle='-') if show: pl.show()
def plot_confussion_matrix(y_true, y_pred): cm_array = confusion_matrix(y_true, y_pred) df_cm = pd.DataFrame(cm_array, columns=np.unique(y_true), index=np.unique(y_true)) df_cm.index.name = 'Actual' df_cm.columns.name = 'Predicted' fig, ax = plt.subplots(figsize=(6, 5)) ax.set_title('Confussion Matrix') ax.yaxis.set_major_locator(ticker.IndexLocator(base=1, offset=0.5)) sns.heatmap(df_cm, cmap='Blues', annot=True, fmt='g', ax=ax) ax.set(yticks=[0, 2], xticks=[0, 1]) fig.savefig('./images/confussion_matrix.png') plt.show()
def _ticker(self): ''' Return the sequence of ticks (colorbar data locations), ticklabels (strings), and the corresponding offset string. ''' locator = self.locator formatter = self.formatter if locator is None: if self.boundaries is None: if isinstance(self.norm, colors.NoNorm): nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=0) elif isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries locator = ticker.FixedLocator(b, nbins=10) elif isinstance(self.norm, colors.LogNorm): locator = ticker.LogLocator() else: locator = ticker.MaxNLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.NoNorm): intv = self._values[0], self._values[-1] else: intv = self.vmin, self.vmax locator.create_dummy_axis(minpos=intv[0]) formatter.create_dummy_axis(minpos=intv[0]) locator.set_view_interval(*intv) locator.set_data_interval(*intv) formatter.set_view_interval(*intv) formatter.set_data_interval(*intv) b = np.array(locator()) if isinstance(locator, ticker.LogLocator): eps = 1e-10 b = b[(b <= intv[1] * (1 + eps)) & (b >= intv[0] * (1 - eps))] else: eps = (intv[1] - intv[0]) * 1e-10 b = b[(b <= intv[1] + eps) & (b >= intv[0] - eps)] ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t, i) for i, t in enumerate(b)] offset_string = formatter.get_offset() return ticks, ticklabels, offset_string
def draw(fdata, pdata): ddata = (fdata.T / fdata.max(axis=1)).T.copy() color_text = '#9b9ba3' locale.setlocale(locale.LC_TIME, "es_US.UTF8") rcParams['font.family'] = 'Quicksand' f = plt.figure(figsize=(40,50), facecolor='#f9f9f9') plt.subplots_adjust(wspace=0.04) gs = f.add_gridspec(1, 6) heat_ax = f.add_subplot(gs[:, :-1]) bar_ax = f.add_subplot(gs[:, -1]) datelist = dates.date2num(ddata.columns.to_pydatetime()) im = heat_ax.imshow(ddata, cmap='Spectral_r', aspect='auto', extent=[datelist[0], datelist[-1], len(ddata), 0], alpha=.8) heat_ax.yaxis.set_major_locator(ticker.FixedLocator([i + 0.5 for i in list(range(0,len(ddata)))])) heat_ax.yaxis.set_minor_locator(ticker.IndexLocator(1,0)) heat_ax.set_yticklabels(ddata.index.tolist()) heat_ax.xaxis.set_major_locator(dates.AutoDateLocator()) heat_ax.xaxis.set_major_formatter(dates.DateFormatter('%B')) heat_ax.grid(axis='x', which='major', alpha=.8, color='white', linewidth=4, linestyle='-') heat_ax.grid(axis='y', which='minor', alpha=.1, color='white', linewidth=1, linestyle='-') heat_ax.tick_params(which='both', axis='both', labelcolor=color_text, labeltop=True, pad=12, rotation=0, width=0, length=0) heat_ax.tick_params(axis='x', labelsize=20) heat_ax.tick_params(axis='y', labelsize=15) heat_ax.set_ylabel('Municipios', fontdict={'size':100, 'family':'Charter'}, color=color_text, labelpad=35) heat_ax.annotate(text='Casos Activos Diarios', xy=(.5,0.94), xycoords='figure fraction', ha='center', va='bottom', color=color_text, fontsize=120, fontfamily='Charter') heat_ax.annotate(text='como proporción del valor máximo por municipio', xy=(.5,0.935), xycoords='figure fraction', ha='center', va='top', color=color_text, fontsize=50, fontfamily='Charter') heat_ax.annotate(text='El número de casos activos en un día corresponde al número de casos que han sido confirmados en los últimos 14 días.\nEn base a datos producidos por el Ministerio de Desarrollo Productivo y Economía Plural y almacenados en https://github.com/mauforonda/covid19bolivia-municipal', xy=(.5,0.040), xycoords='figure fraction', ha='center', va='bottom', color=color_text, fontsize=25, fontfamily='Charter', linespacing=1.6) pdata[::-1].plot(kind='barh', ax=bar_ax, color='#8f5383', alpha=.7, width=0.9) bar_ax.set_yticks([]) bar_ax.tick_params(axis='x', labeltop=True, labelcolor=color_text, labelsize=20, pad=12, rotation=0, width=0, length=0) bar_ax.grid('x', 'major', alpha=.3, color=color_text, linewidth=2, linestyle='-') bar_ax.xaxis.set_major_locator(ticker.MaxNLocator(3)) bar_ax.set_xlabel('Casos acumulados\npor 100 Mil habitantes', fontdict={'size':30, 'family':'Charter'}, color=color_text, labelpad=40, loc='left') bar_ax.xaxis.set_label_position('top') bar_ax.set_ylabel('') for ax in [heat_ax, bar_ax]: ax.set_frame_on(False) plt.savefig('plots/municipios_heatmap.jpg', bbox_inches='tight', dpi=100, pad_inches=0.8) plt.close()
def _ticker(self): ''' Return two sequences: ticks (colorbar data locations) and ticklabels (strings). ''' locator = self.locator formatter = self.formatter if locator is None: if self.boundaries is None: if isinstance(self.norm, colors.NoNorm): nv = len(self._values) base = 1 + int(nv/10) locator = ticker.IndexLocator(base=base, offset=0) elif isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries locator = ticker.FixedLocator(b, nbins=10) elif isinstance(self.norm, colors.LogNorm): locator = ticker.LogLocator() else: locator = ticker.MaxNLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.NoNorm): intv = self._values[0], self._values[-1] else: intv = self.vmin, self.vmax locator.create_dummy_axis() formatter.create_dummy_axis() locator.set_view_interval(*intv) locator.set_data_interval(*intv) formatter.set_view_interval(*intv) formatter.set_data_interval(*intv) # the dummy axis is expecting a minpos locator.axis.get_minpos = lambda : intv[0] formatter.axis.get_minpos = lambda : intv[0] b = np.array(locator()) b, ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t, i) for i, t in enumerate(b)] offset_string = formatter.get_offset() return ticks, ticklabels, offset_string
def _select_locator(self): """Select a suitable locator.""" if self.boundaries is None: if isinstance(self.norm, colors.NoNorm): nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=0) elif isinstance(self.norm, colors.BoundaryNorm): b = self.norm.boundaries locator = ticker.FixedLocator(b, nbins=10) elif isinstance(self.norm, colors.LogNorm): locator = ticker.LogLocator() else: locator = ticker.MaxNLocator(nbins=5) else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b) self.cbar_axis.set_major_locator(locator)
def draw_line_rtt(self, fig, ax, scale: str): # tune data self.df_ext_rtt = self.df_scaled['avg_rtt']['External'].copy() self.df_ext_rtt.clip_upper(PING_THRESHOLD, inplace=True) # draw # ax.plot(self.df_ext_rtt) # self.df_ext_rtt.plot.line(ax=ax, grid=True, use_index=False, title=f"Last {scale}") # set axes ax.xaxis.set_major_locator( ticker.IndexLocator(self.scales[scale]['x_base'], 0.5)) ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.tick_params(axis='x', labelrotation=90.) # set y axis ax.set_ylabel('Average ping\nto outside (in ms)')
def scatterplot(self, labels=SAMPLE_LABELS_SCATTER, data=SAMPLE_DATA_SCATTER): # use a grid with 2 rows and 6 columns # position plot in the lower left place on the pot window # span 3 columns wide ax3 = plt.subplot2grid((2, 6), (1, 0), colspan=3) # sort data to display most recent datapoints to the right (timeline) labels, data = sort_weekdays(labels, data) # set label to the far right as 'today' labels[-1] = 'Now' # use no labels on major ticks # use a fixed set of labels on minor ticks ax3.xaxis.set_major_formatter(ticker.NullFormatter()) ax3.xaxis.set_minor_formatter(ticker.FixedFormatter(labels)) # compute exact position for minor ticks ticks = [] pos = np.arange(len(data)) for i in range(len(labels)): # position seven ticks between the major ticks tmp = int((i + 0.5) * len(data) // len(labels)) ticks.append(pos[tmp]) # set major ticks to work with 7 labels (8 ticks will be set) # set minor ticks on their positions ax3.xaxis.set_major_locator(ticker.IndexLocator(24, 0)) ax3.xaxis.set_minor_locator(ticker.FixedLocator(ticks)) # hide minor tick markers for tick in ax3.xaxis.get_minor_ticks(): tick.tick1line.set_markersize(0) # set labels for axes and plot title ax3.set_ylabel('Hashtag Count') ax3.set_title('Performance') # display the plot ax3.scatter(pos, data, marker='.', s=1) ax3.plot(pos, data)