def set_cmap(self, cmap): """ Change the colormap of the image """ if cmap == 'autumn': plt.autumn() elif cmap == 'spring': plt.spring() self.canvas.show()
def show_training_stats(self, models_stats=None): plt.autumn() fig = plt.figure(figsize=(7, 7), dpi=100) plt.yticks(np.arange(0, 1.2, 0.1)) # fig.suptitle("Training accuracy") if models_stats is not None: # Stats of each model spi = 0 # subplot index n_subplots = len(models_stats.items()) # total number of subplots row_labels = [] row_data = [] for name, data in models_stats.items(): spi += 1 ax = fig.add_subplot(n_subplots, 1, spi) # Each epoch stats of each model table_col_labels = [] cell_data = [] for i, ep in enumerate(data['training']): ax.plot('n_samples', 'accuracy', data=ep, label="Epoch " + str(i + 1), linestyle='solid') cell_data.append("{}%".format( round(ep['accuracy'][-1] * 100, 2))) table_col_labels.append("Epoch " + str(i + 1)) row_labels.append(name + " training accuracy") row_data.append(cell_data) ax.set_ylabel("Accuracy") ax.legend() ax.grid(alpha=0.3, linewidth=1, ls='dashed') ax.set_title(str(name) + " Training Accuracy") ax.set_yticks(np.arange(0.0, 1.1, 0.1)) ax.set_yticklabels(np.round(np.arange(0.0, 1.0, 0.1), 1)) if spi == n_subplots: spacer = -0.7 else: spacer = -0.5 ax.table(cellText=[cell_data], rowLabels=["Accuracy"], colLabels=table_col_labels, loc='bottom', cellLoc='center', rowLoc='center', bbox=(0.1, spacer, 0.9, 0.3)) if len(models_stats.items()) == 1: bottom = 0.4 else: bottom = 0.29 plt.subplots_adjust(hspace=0.98, bottom=bottom, top=0.9) plt.xlabel("Number of samples")
def imshow(image, **kwargs): """ Show image. """ import matplotlib.pyplot as plt plt.autumn() plt.imshow(image, **kwargs) plt.tick_params(label1On=False, tick1On=False, tick2On=False) plt.tight_layout() plt.show()
def correl_bar_chart(indices, date, db): if indices: index_names = [] for index in indices: index_names.append(Repository.index_name(index)) query = ''' SELECT "index", avg_correl FROM histo_correlation WHERE "index" in ('%s') and date = ? ORDER BY avg_correl DESC ''' % ("','".join(index_names)) else: query = ''' SELECT "index", avg_correl FROM histo_correlation WHERE date = ? ORDER BY avg_correl DESC ''' rows = db.select(query, date.strftime('%Y%m%d')) avg_correl = [row[1] for row in rows] fig = plt.figure() fig.set_size_inches(7., 7.) ax = fig.add_subplot(111) plt.subplots_adjust(left=0.05, bottom=0.15, right=0.98, top=0.98, wspace=0, hspace=0) plt.grid(True) pos = np.arange(len(rows)) + 0.5 #Center bars on the Y-axis ticks rects = ax.barh(pos, avg_correl, align='center', height=0.5) ax.axis([0,1,0,len(rows)]) pylab.yticks([]) for i, rect in enumerate(rects): width = float(rect.get_width()) #if width < len(rows[i][0]): # The bars aren't wide enough to print the ranking inside # xloc = width + 1 # Shift the text to the right side of the right edge # clr = 'black' # Black against white background # align = 'left' #else: xloc = 0.02 * width # Shift the text to the left side of the right edge clr = 'white' # White on magenta align='left' yloc = rect.get_y() + rect.get_height()/2.0 # Center the the text vertically in the bar ax.text(xloc, yloc, rows[i][0], horizontalalignment=align, verticalalignment='center', color = clr, weight='bold') pylab.xlabel('Average Correlation') plt.autumn() plt.savefig(os.path.join(CHART_DIR, 'correl_%s' % date.strftime('%Y%m%d')),dpi=(300))
def make_graph(dataset, outputfile): # TODO: handle edge case if data is empty offset = timedelta(minutes=10) duration = max([v[-1][0] - v[0][0]+offset for v in dataset.values()]) locator = mdates.AutoDateLocator(minticks=6) formatter = mdates.ConciseDateFormatter(locator) fig, ax = plt.subplots() ax.xaxis.set_major_locator(locator) ax.xaxis.set_major_formatter(formatter) for name, data in dataset.items(): if name == "test": # len(data) < 10 or logger.warning(f"skipping '{name}'") continue logger.debug(f"{name} start: {data[0][0]}") logger.debug(f"{name} end: {data[-1][0]}") x_list, y_list_raw = zip(*data) y_list = clean_whacky(y_list_raw) x = numpy.array(x_list) y = numpy.array(y_list) logger.debug(f"{len(x_list)} datapoints") plt.autumn() ax.plot(x, y, label=name) ax.legend(loc="best") #ax.legend(bbox_to_anchor=(1.1, 1.05)) header = get_header(duration) logger.info(f"plotted '{header}'") plt.title(header) plt.ylabel("Celcius") plt.savefig(outputfile, format="png") if isinstance(outputfile, str): logger.info(f"wrote '{outputfile}'") return len(data)
def plot_polar_contour(values, azimuths, zeniths): """Plot a polar contour plot, with 0 degrees at the North. Arguments: * `values` -- A list (or other iterable - eg. a NumPy array) of the values to plot on the contour plot (the `z` values) * `azimuths` -- A list of azimuths (in degrees) * `zeniths` -- A list of zeniths (that is, radii) The shapes of these lists are important, and are designed for a particular use case (but should be more generally useful). The values list should be `len(azimuths) * len(zeniths)` long with data for the first azimuth for all the zeniths, then the second azimuth for all the zeniths etc. This is designed to work nicely with data that is produced using a loop as follows: values = [] for azimuth in azimuths: for zenith in zeniths: # Do something and get a result values.append(result) After that code the azimuths, zeniths and values lists will be ready to be passed into this function. """ r, theta = np.meshgrid(zeniths, np.radians(azimuths)) fig, ax = plt.subplots(subplot_kw=dict(projection='polar')) ax.set_theta_zero_location("N") ax.set_theta_direction(-1) plt.autumn() cax = ax.contourf(theta, r, values, 30) cb = fig.colorbar(cax) cb.set_label("Pixel reflectance") return fig, ax, cax
toplot = np.empty(X.shape) for i in range(X.shape[0]): for j in range(X.shape[1]): toplot[i, j] = pred.predict(np.array([X[i, j], Y[i, j]]).reshape(1, -1)) Z_sol = used_model(tf.cast(design_tf, tf.float32)).numpy() fig, ax = plt.subplots() im = ax.imshow(toplot, interpolation='bilinear', origin='lower', cmap=cm.gray, extent=extent) plt.scatter(Z_sol[:, 0], Z_sol[:, 1], c=response) plt.autumn() plt.show() plt.savefig('images/ackley_before.pdf') ## Estimate the weights! est_model = update_weights(design, response, used_model, l2_coef=0.5) ## Get the extent of the design with many points. viz_design = neural_maxent(100, P, L, H, R, net_weights=est_model.get_weights())['design'] viz_Z = est_model(tf.cast(viz_design, tf.float32)).numpy() extent = [
import pandas as pd import matplotlib.pyplot as plot import numpy as np shh=pd.read_csv("/home/koreanraichu/rheumatism.csv",sep=";") shh=shh.dropna() # Nan은 친절하게 보내드렸습니다 x=pd.to_numeric(shh['HBA']) y=pd.to_numeric(shh['HBD']) # 글자라 정렬 개판돼서 숫자로 바꿔버림(Nan때문인가 암만봐도 숫자인데 object로 불러옴) xtick=list(range(1,12,2)) # 축 간격용 리스트 area=75 # 여기 면적 추가요 np.random.seed(0) """ 이제 이 밑부분은 그래프 영역입니다. 끝. """ fig,ax=plot.subplots() ax.set_xlabel('Hydrogen bond acceptor') ax.set_ylabel('Hydrogen bond donor') plot.rc("font", family='Nanumgothic') plot.title('HBA/HBD') plot.scatter(x,y,label="HBA/HBD",s=area,alpha=0.8,c=y) # HBD 숫자에 따라 색깔이 달라지게 설정했다. (HBA는 x로 주면 될 듯 하다) #어? 이거 모양 바꿔도 적용되네? plot.autumn() # 컬러맵 추가 plot.colorbar() #컬러바 추가 plot.legend(loc=0) # 굳이 넣어야되나... plot.xticks(xtick) plot.savefig('graph.png') plot.show()
A.simplify() # from hermite development MH = Matrix([[2,-2,1,1],[-3,3,-2,-1],[0,0,1,0],[1,0,0,0]]) T = Matrix([[t**3],[t**2],[t],[1]]) MC = MH.multiply(A) MC.simplify() # b(t) = M_C^T t b = MC.T.multiply(T) t_mesh = np.linspace(0,1) plt.autumn() fig = plt.figure() for c_val, subplot_index in zip([0, 0.25, .5, .9], [221,222,223,224]): ax = fig.add_subplot(subplot_index) ax.set_color_cycle(['c','m','y','k']) ax.tick_params(labelsize='small') blends = [lambdify(t, bi) for bi in b.subs(c, c_val)] for i, blend in enumerate(blends, 1): fn_label = r'$b_{}(t)$'.format(i) y = blend(t_mesh) ax.plot(t_mesh, y, label=fn_label, linewidth=2) ax.set_title(r'$c={}$'.format(c_val)) ax.set_ylabel(r'$b_i(t)$') ax.set_xlabel(r'$t$')
def edit_spectrum(config, **kwargs): try: sampling = config[c_sampling] # дискретизация duration = config[c_duration] # задаем границы массива диапазон частот [fmin:fmax] fmin = 1 fmax = int(sampling / 2) if c_freq0 in config and config[c_freq0] in range(fmin, fmax): fmin = config[c_freq0] if c_freq1 in config and config[c_freq1] in range(fmin, fmax): fmax = config[c_freq1] spectrumMax = 100 # в процентах % # spectrum_form_file_name = config[c_spectrum_form_file] # get_path(config, C_SPECTRUM) newForm = 'newForm' in kwargs and kwargs['newForm'] == True ############################################### ver, controls_count, controls, minX, maxX = read_spectrum_form_file( config, **kwargs) # если не удалось прочитать сохраненную форму спектра, то создаем новую if newForm or controls_count is None: controls_count = get_cfg_param(config, c_spec_form_edit_control_count, 41, 'i') # CONTROL_COUNT minX = fmin maxX = fmax # получаем два массива с координатами регуляторов xs, ys = get_xs_ys(minX, maxX, controls_count) # если создаем новую форму спектра, то значения у всех регуляторов равно 100% if newForm or controls is None: ys[1:-1] = spectrumMax else: for i in range(1, controls_count + 1, 1): ys[i] = controls[i - 1] # создаем графические элементы fig, ax = plt.subplots() plt.vlines(xs, 0, ys, label=' ', color='b', lw=3) plt.legend( title= 'Полоса частот %i - %i Гц\nctrl + r - сброс\nctrl + w - сохранить и выйти\n0..9 - установить уровень регулятора' % (minX, maxX), loc='upper left', shadow=True, frameon=True, fontsize='small') plt.axis([fmin, fmax, 0, spectrumMax * 1.5]) plt.xticks( arange(fmin, fmax, int(get_xstep(fmax - fmin, controls_count)) * 2) ) #, arange(0, len(aspec), get_xstep(len(aspec), controls_count) * 4)) poly = Polygon(list(zip(xs, ys)), animated=True, closed=False, color=colorConverter.to_rgba('b', 0.250), visible=True) ax.add_patch(poly) p = PolygonInteractor(ax, poly, config[c_spectrum_form_file], minX, maxX) # , aspec plt.autumn() plt.grid() plt.show() return True except Exception as E: print('error in function edit_spectrum(): ', file=sys.stderr, end='') print(E, file=sys.stderr) return None
for index in range(len(d_l)): if d_l[index] < avg_1: x_l_l.append(x_l[index]) y_l_l.append(y_l[index]) d_l_l.append(d_l[index]) f, ax = plt.subplots() ax.set_title("min - KL-Divergence (%s)" % len(d_l_l)) ax.set_ylabel('density') ax.set_xlabel('q_value') points = ax.scatter(x_l_l, y_l_l, c=d_l_l, s=50, cmap=cmap) f.colorbar(points) plt.ylim((y_min, y_max)) plt.show() cmap = plt.autumn() avg_1 = np.average(d_u) d_u_u = list() x_u_u = list() y_u_u = list() for index in range(len(d_u)): if d_u[index] > avg_1: x_u_u.append(x_u[index]) y_u_u.append(y_u[index]) d_u_u.append(d_u[index]) avg_2 = np.average(d_u_u) d_u = list() x_u = list() y_u = list() for index in range(len(d_u_u)):