def showmat(name, mat, alpha, beta): sample_dir = 'samples/' alpha = [a.decode('utf-8') for a in alpha] beta = [b.decode('utf-8') for b in beta] fig = plt.figure(figsize=(20, 20), dpi=80) plt.clf() matplotlib.rcParams.update({'font.size': 12}) ax = fig.add_subplot(111) ax.set_aspect(1) ax.xaxis.tick_top() res = ax.imshow(mat, cmap=plt.cm.Blues, interpolation='nearest') font_prop = FontProperties() font_prop.set_file( 'D:\users\chxing\\aaai2017Exp\\filterDouban\data.r50.q1min30max.tokenized.2-20.1-20\model_for_test\\attention\\simfang.ttf' ) font_prop.set_size('large') plt.xticks(range(len(alpha)), alpha, rotation=60, fontproperties=font_prop) plt.yticks(range(len(beta)), beta, fontproperties=font_prop) cax = plt.axes([0.0, 0.0, 0.0, 0.0]) plt.colorbar(mappable=res, cax=cax) plt.savefig(name + '.png', format='png') plt.close()
def draw_annot_by_text(file_name, image_dir,GT_dir,output_dir, isGT=True, inch=40, font_path=None, draw_bbox=True): for file in file_name: print('Draw predicted result to file', file) GT_file = os.path.join(GT_dir, file + '.txt') img_path = os.path.join(image_dir, file + '.png') if os.path.exists(os.path.join(image_dir, file + '.jpg')): img_path = os.path.join(image_dir, file + '.jpg') content = [] with codecs.open(GT_file, 'r', encoding='utf8') as f: for line in f: content.append(line.replace('\n', '')) fig, ax = plt.subplots(1) fig.set_size_inches(inch, inch) ori_img = cv2.imread(img_path, cv2.IMREAD_IGNORE_ORIENTATION | cv2.IMREAD_COLOR) img = cv2.cvtColor(ori_img, cv2.COLOR_RGB2GRAY) plt.imshow(img, cmap='Greys_r') for c in content: #print(str(c)) obj = c.split(" ") class_nm = obj[0] color = 'b' conf = 1.0 if not isGT: conf = float(obj[1]) xmin = int(obj[2]) ymin = int(obj[3]) width = int(obj[4]) height = int(obj[5]) else: xmin = int(obj[1]) ymin = int(obj[2]) width = int(obj[3]) height = int(obj[4]) if (conf >= 0.8 and conf < 0.9): color = 'cyan' if(conf>=0.7 and conf<0.8): color = 'green' if(conf>=0.6 and conf<0.7): color = 'orange' if(conf>=0.5 and conf<0.6): color = 'red' if(conf<0.5): color = 'black' if (height > 0): if font_path is None: plt.text(xmin - 2, ymin - 4, class_nm, fontsize=max(int(height / 2), 12), fontdict={"color": 'r'}) else: prop = FontProperties() prop.set_file(font_path) plt.text(xmin-2, ymin-4, class_nm, fontsize= max(int(height/2), 1), fontdict={"color": 'r'}, fontproperties=prop) if not draw_bbox and color=='b': continue ax.add_patch(patches.Rectangle((xmin, ymin), width, height, linewidth=2, edgecolor=color, facecolor='none')) # plt.show() save_img_path=os.path.join(output_dir,file+'_visualize_result.jpg') fig.savefig(save_img_path,bbox_inches='tight')
def main(): # Font properties to show unicode symbols on plot global prop prop = FontProperties() prop.set_file(FONT_PROPERTIES_TTF_FILE) rad, dens, pres = read_model() plot_density(rad, dens) plot_pressure(rad, pres)
def ramachandran(self): """ Plots the torsion anlge as a ramachandran plot. """ prop = FontProperties() prop.set_file('resources/STIXGeneral.ttf') ax = plt.scatter(self.phi, self.psi) plt.xlabel(u"\u03C6", fontproperties=prop) plt.ylabel(u"\u03C8", fontproperties=prop) plt.show()
def plot_gammaB_energy(path, file_name, gamma_dict, total_energy): """Create the plot of gamma*b to energy in log scale.""" plot_gamma = list(gamma_dict.keys()) gamma_array = list(gamma_dict.values()) plot_ener = [] for i in range(len(gamma_array)): plot_ener.append(sum(gamma_array[i:])) plot_ener_integral = [i / total_energy for i in plot_ener ] # ratio of energy to the total energy plot_ener_single = [i / total_energy for i in gamma_array] prop = FontProperties() # Font properties to show unicode symbols on plot prop.set_file(FONT_PROPERTIES_TTF_FILE) name = f'result_ener_vel_{file_name}' if not args.overlap: plt.clf() else: name = f'result_ener_vel_overlap_{file_name}' # default style for plot plt.rcdefaults() plt.rcParams['figure.figsize'] = [10, 10] plt.subplots_adjust(hspace=0.5) plt.style.use('ggplot') # Plot cumulative plt.subplot(2, 1, 1) plt.plot(plot_gamma, plot_ener_integral) plt.legend() plt.xlabel(G + B, fontproperties=prop) plt.ylabel(f'E(>{G}{B})/E0', fontproperties=prop) plt.ylim(BOTTOM, TOP) plt.xlim(LEFT, RIGHT) plt.xscale('log') plt.yscale('log') plt.title('Lorentz factor to energy distribution (cumulative)') # Plot non-cumulative plt.subplot(2, 1, 2) plt.plot(plot_gamma, plot_ener_single) plt.legend() plt.xlabel(G + B, fontproperties=prop) plt.ylabel(f'E({G}{B})/E0', fontproperties=prop) plt.ylim(BOTTOM, TOP) plt.xlim(LEFT, 2E2) plt.xscale('log') plt.yscale('log') plt.title('Lorentz factor to energy distribution (non-cumulative)') # Save to file plt.savefig(f'{path}\\{name}.pdf', bbox_inches='tight')
def get_ds_font(fontName="OpenSans-Regular.ttf"): """ 载入字体 "OpenSans-Regular.ttf" "simhei.ttf" "微软雅黑.ttf" """ selfpath = os.path.split(os.path.realpath(__file__))[0] font0 = FontProperties() font_path = os.path.join(selfpath, "FNT", fontName) if os.path.isfile(font_path): font0.set_file(font_path) return font0 return None
def get_DS_Font(fontName='OpenSans-Regular.ttf'): ''' 载入字体 'OpenSans-Regular.ttf' 'simhei.ttf' '微软雅黑.ttf' ''' selfpath = os.path.split(os.path.realpath(__file__))[0] font0 = FontProperties() font_path = os.path.join(selfpath, 'FNT', fontName) if os.path.isfile(font_path): font0.set_file(font_path) return font0 return None
def graph_maker_bar(active, deaths, recovered, filename): x = ["Active cases", "Deaths", "Recovered"] y = [active, deaths, recovered] colours = ["#F79F1F", "#EA2027", "#4cd137"] plt.style.use("dark_background") fig, ax = plt.subplots(dpi=150) for i in range(0, len(x)): ax.bar(x[i], y[i], 0.75, align="center", color=colours[i] ) ax.yaxis.set_major_formatter(ticker.FuncFormatter(format_values)) plt.minorticks_off() plt.xticks(fontsize=font_size) plt.yticks(fontsize=font_size) fig.autofmt_xdate(rotation=0, ha="center") ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.grid(which="both", axis="y", color="grey", linewidth=grid_line_width, alpha=grid_opacity ) title_font = FontProperties() title_font.set_family("sans-serif") title_font.set_file("./Whitney-Font/whitney-semibold.otf") title_font.set_size(14) title_pad = 18 ax.set_title(f"Bar chart", pad=title_pad, fontproperties=title_font) plt.savefig(f"{filename}.png", transparent=True) # plt.show() fig.clear() plt.close(fig)
def graph_maker_list_bar(numbers, country_codes, filename): x = country_codes y = numbers colour_list = ["#F44336", "#4CAF50", "#3F51B5", "#9C27B0", "#03A9F4", "#CDDC39"] plt.style.use("dark_background") fig, ax = plt.subplots(dpi=150) for i in range(0, len(x)): ax.bar(x[i], y[i], 0.75, align="center", color=colour_list[i] ) ax.yaxis.set_major_formatter(ticker.FuncFormatter(format_values)) plt.minorticks_off() plt.xticks(fontsize=font_size) plt.yticks(fontsize=font_size) fig.autofmt_xdate(rotation=0, ha="center") ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.grid(which="both", axis="y", color="grey", linewidth=grid_line_width, alpha=grid_opacity ) title_font = FontProperties() title_font.set_family("sans-serif") title_font.set_file("./Whitney-Font/whitney-semibold.otf") title_font.set_size(14) title_pad = 18 ax.set_title(f"Bar chart", pad=title_pad, fontproperties=title_font) plt.savefig(f"{filename}.png", transparent=True) # plt.show() fig.clear() plt.close(fig)
def get_DV_Font(fontName=None): ''' 载入字体 'OpenSans-Regular.ttf' 'simhei.ttf' 'winhei.ttf' 微软雅黑 ''' font0 = FontProperties() if fontName: font_path = os.path.join(selfPath, 'FNT', fontName) if os.path.isfile(font_path): font0.set_file(font_path) return font0 # 默认字体 font_path = os.path.join(selfPath, 'FNT', "SourceHanSansCN-Normal.otf") font0.set_file(font_path) return font0
def plot_with_labels(low_dim_embs, labels, filename='tsne.png'): assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings" # To show UTF-8 Chinese glyphs, these 2 lines are needed from matplotlib.font_manager import FontProperties prop = FontProperties() prop.set_file('wt064.ttf') # [TODO] Specify a font (or at least solve this problem more elegantly) plt.figure(figsize=(20, 20)) #in inches for i, label in enumerate(labels): x, y = low_dim_embs[i,:] plt.scatter(x, y) plt.annotate(label, xy=(x, y), xytext=(5, 2), textcoords='offset points', ha='right', va='bottom', fontproperties=prop) plt.savefig(filename)
def get_DV_Font(fontName=None): """ 载入字体 'OpenSans-Regular.ttf' 'simhei.ttf' 'winhei.ttf' 微软雅黑 """ font0 = FontProperties() if fontName: font_path = selfPath / 'FNT' / fontName if font_path.is_file(): # os.path.isfile(font_path): font0.set_file(str(font_path)) return font0 # 默认字体 # font_path = str(selfPath / 'FNT' / "SourceHanSansCN-Normal.otf") font_path = str(selfPath / 'FNT' / "sarasa-ui-sc-regular.ttf") font0.set_file(font_path) return font0
def showmat(name, mat, alpha, beta): sample_dir = 'samples/' alpha = [a.decode('utf-8') for a in alpha] beta = [b.decode('utf-8') for b in beta] fig = plt.figure(figsize=(20, 20), dpi=80) plt.clf() matplotlib.rcParams.update({'font.size': 18}) ax = fig.add_subplot(111) ax.set_aspect(1) ax.xaxis.tick_top() res = ax.imshow(mat, cmap=plt.cm.Blues, interpolation='nearest') font_prop = FontProperties() font_prop.set_file('./wqy-zenhei.ttf') font_prop.set_size('large') plt.xticks(range(len(alpha)), alpha, rotation=60, fontproperties=font_prop) plt.yticks(range(len(beta)), beta, fontproperties=font_prop) cax = plt.axes([0.0, 0.0, 0.0, 0.0]) plt.colorbar(mappable=res, cax=cax) plt.savefig(name + '.png', format='png') plt.close()
from keras.layers import Input, Dense, Activation, BatchNormalization from keras.layers import Reshape, Lambda, GlobalAveragePooling2D from keras.layers.merge import add, concatenate from keras.models import Model from keras.layers.recurrent import GRU # from keras.optimizers import SGD from keras.utils.data_utils import get_file from keras.preprocessing import image import keras.callbacks from matplotlib.font_manager import FontProperties from keras.utils import to_categorical # matplotlib.rc('font', family="Lohit Devanagari") prop = FontProperties(size=16) prop.set_file('fonts/Sarun_ThangLuang.ttf') OUTPUT_DIR = 'image_ocr_LP' # character classes and matching regex filter regex = r'^[a-z ]+$' # alphabet = u'abcdefghijklmnopqrstuvwxyz ' alphabet = u'กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮ๑๒๓๔๕๖๗๘๙๐0123456789 ' np.random.seed(55) # this creates larger "blotches" of noise which look # more realistic than just adding gaussian noise # assumes greyscale with pixels ranging from 0 to 1 def speckle(img):
def main(argv): note_labels = ["C", 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'] if len(argv) < 3: return notes = np.load(argv[1]) if notes.shape[-1] == 5: notes = notes[:,:,:,:,[2,4]] notes = notes[:20] notes = notes.reshape((20,4,48,84,2)) # 48 for lakh, 8 for ours notes[notes < 0] = 0 notes[notes > 0] = 1 # Pitch metrics pitches = np.amax(notes.transpose(0,1,2,4,3).flatten().reshape(-1,84), axis=0) pc = np.sum(pitches) print("pitch count: {}".format(pc)) ranges = np.nonzero(pitches)[0] pr = ranges[-1] - ranges[0] print("pitch range: {}".format(pr)) # Pitch and note metrics histogram = np.zeros(12) transitions = np.zeros((12,12)) note_histogram = np.zeros(6) note_tr = np.zeros((6,6)) music = notes.reshape(-1,84,2).transpose(2,0,1) lengths = {} lengths2 = set() lastlastlength = -1 lastlength = -1 for track in music: for i in range(0, music.shape[1]-5, 4): indices = np.nonzero(track[i])[0] % 12 ls = [] #print(indices) for l in lengths.keys(): if l not in indices: lastlastlength = lastlength if l == 1: note_histogram[0] += 1 #8th lastlength = 0 elif l == 2: note_histogram[1] += 1 #quarter lastlength = 1 elif l == 3: note_histogram[2] += 1 #quarter dot lastlength = 2 elif l == 4: note_histogram[3] += 1 #half lastlength = 3 elif l <= 6: note_histogram[4] += 1 #half dot lastlength = 4 elif l <= 8: note_histogram[5] += 1 lastlength = 5 ls.append(l) lengths2.add(l) else: lengths[l] += 1 if lastlastlength > 0 and lastlength > 0: note_tr[lastlastlength][lastlength] += 1 for l in ls: del lengths[l] for l in indices: if l not in lengths: lengths[l] = 1 histogram[indices] += 1 next_indices = np.nonzero(track[i+1])[0] % 12 i1 = indices#np.asarray(list(set(indices).difference(next_indices)), dtype='int64') #print(indices, next_indices) i2 = next_indices#np.asarray(list(set(next_indices).difference(indices)), dtype='int64') #print(i1, i2) transitions[i1.repeat(len(i2)),np.tile(i2, len(i1))] += 1 indices = np.nonzero(track[-1])[0] % 12 histogram[indices] += 1 plt.bar(range(12), histogram) plt.yticks([]) plt.xticks(range(12), note_labels) plt.savefig(argv[2] + '_pch.png') print('pitch histogram saved') plt.clf() #fig, ax = plt.subplots() transitions_norm = transitions / max(1, transitions.max()) plt.xticks(range(12), note_labels) plt.yticks(range(12), note_labels) plt.imshow(transitions_norm, cmap='jet') plt.colorbar() plt.savefig(argv[2] + '_pctm.png') print('pitch transitions saved') plt.clf() nc = len(lengths2) prop = FontProperties() prop.set_file('FreeSerif.ttf') print('note count {}'.format(nc)) fig, ax = plt.subplots() symbolsx = [u"\U0001D160", u"\U0001D15F", u"\U0001D15F\U0001D16D", u"\U0001D15E", u"\U0001D15E\U0001D16D", u"\U0001D15D"] plt.bar(range(6), note_histogram) ax.set_xticks(range(len(symbolsx))) ax.set_xticklabels(symbolsx, fontsize=500, fontproperties=prop) ax.set_yticks([]) plt.savefig(argv[2] + '_nlh.png') plt.clf() print('note histogram saved') transitions_norm = note_tr / max(1, note_tr.max()) plt.xticks(range(6), symbolsx, size=500, fontproperties=prop) plt.yticks(range(6), symbolsx, size=500, fontproperties=prop) plt.imshow(transitions_norm, cmap='jet') plt.colorbar() plt.savefig(argv[2] + '_nctm.png') plt.clf() print('note transitions saved')
from matplotlib.font_manager import FontProperties from numpy import * from pylab import * # Define vectors and scalars x = array([1, 2]) y = array([2, 1]) z = x + y half_x = 0.5 * x two_x = 2 * x # Plot vectors fig = figure(figsize=(20, 8)) suptitle('Simple Vector Operations') prop = FontProperties() prop.set_file('STIXMath-Regular.otf') subplot(1, 2, 1) quiver((0, 0, 0), (0, 0, 0), (two_x[0], x[0], half_x[0]), (two_x[1], x[1], half_x[1]), angles='xy', scale_units='xy', scale=1, color=('purple', 'r', 'b')) labels = [u'2x = \u27E82, 4\u27E9', u'x = \u27E81, 2\u27E9', u'0.5x = \u27E80.5, 1\u27E9'] xs = [two_x[0], x[0], half_x[0]] ys = [two_x[1], x[1], half_x[1]] for label, u, v in zip(labels, xs, ys): annotate(label, xy = (u + 0.05, v), fontproperties=prop) title('Scalar Product') xlim([0, 5]) ylim([0, 5]) draw() subplot(1, 2, 2) plot((x[0], z[0]), (x[1], z[1]), '--r')
def graph_maker_list(country_code_list, filename, cases_type="confirmed", graph_type="linear"): country_code_list_upper = [] x = [] colour_list = ["#F44336", "#4CAF50", "#3F51B5", "#9C27B0", "#03A9F4", "#CDDC39"] if len(country_code_list) <= country_limit: plt.style.use("dark_background") fig, ax = plt.subplots(dpi=150) y = [] for u in range(0, len(country_code_list)): url_graph = f"https://api.covid19api.com/total/country/{country_code_list[u]}/status/{cases_type}" response = requests.get(url_graph) data_graph = response.json() country_code_list_upper.append(str.upper(country_code_list[u])) if u == 0: for i in range(0, len(data_graph)): day = str(data_graph[i]["Date"][8:10]) month = date_formatter(str(data_graph[i]["Date"][5:7])) dates = month + " " + day x.append(dates) y.append([]) for i in range(0, len(data_graph)): value = per_mil_calculator(data_graph[i]["Country"], data_graph[i]["Cases"]) y[u].append(value) ax.plot(x, y[u], color=colour_list[u], linewidth=line_width, marker=".", markerfacecolor=colour_list[u], markersize=marker_size ) ax.fill_between(x, 0, y[u], facecolor=colour_list[u], alpha=0.25) title_font = FontProperties() title_font.set_family("sans-serif") title_font.set_file("./Whitney-Font/whitney-semibold.otf") title_font.set_size(14) title_pad = 18 if graph_type == "linear": ax.set_title(f"Linear graph", pad=title_pad, fontproperties=title_font) plt.yscale("linear") elif graph_type == "log": ax.set_title(f"Logarithmic graph", pad=title_pad, fontproperties=title_font) plt.yscale("log") plt.ylim(bottom=y_limit) plt.minorticks_off() ax.yaxis.set_major_formatter(ticker.FuncFormatter(format_values)) plt.xticks(fontsize=font_size) plt.yticks(fontsize=font_size) ax.xaxis.set_major_locator(ticker.IndexLocator(base=20, offset=2)) fig.autofmt_xdate(rotation=0, ha="center") ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.grid(which="both", axis="y", color="grey", linewidth=grid_line_width, alpha=grid_opacity ) ax.legend(country_code_list_upper, prop={"size": legend_size}, fancybox=True, facecolor="0.25") plt.savefig(f"{filename}.png", transparent=True) # plt.show() fig.clear() plt.close(fig)
def graph_maker(graph_type, country_code, filename): url_cases = f"https://api.covid19api.com/total/country/{country_code}/status/confirmed" response_cases = requests.get(url_cases) data_cases = response_cases.json() url_deaths = f"https://api.covid19api.com/total/country/{country_code}/status/deaths" response_deaths = requests.get(url_deaths) data_deaths = response_deaths.json() # url_recovered = f"https://api.covid19api.com/total/country/{country_code}/status/recovered" # response_recovered = requests.get(url_recovered) # data_recovered = response_recovered.json() x = [] y = [] y1 = [] # y2 = [] for i in range(0, len(data_cases)): day = str(data_cases[i]["Date"][8:10]) month = date_formatter(str(data_cases[i]["Date"][5:7])) dates = month + " " + day x.append(dates) y.append(data_cases[i]["Cases"]) y1.append(data_deaths[i]["Cases"]) # y2.append(data_recovered[i]["Cases"]) # https://www.geeksforgeeks.org/graph-plotting-in-python-set-1/ # https://towardsdatascience.com/customizing-plots-with-python-matplotlib-bcf02691931f plt.style.use("dark_background") fig, ax = plt.subplots(dpi=150) # Plot confirmed cases ax.plot(x, y, color="#F79F1F", linewidth=line_width, marker=".", markerfacecolor="#F79F1F", markersize=marker_size ) # Plot deaths ax.plot(x, y1, color="#EA2027", linewidth=line_width, marker=".", markerfacecolor="#EA2027", markersize=marker_size ) # Plot recovered # ax.plot(x, y2, # color="#4cd137", # linewidth=line_width, # marker=".", # markerfacecolor="#4cd137", # markersize=marker_size # ) # https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-locators.html ax.xaxis.set_major_locator(ticker.IndexLocator(base=20, offset=2)) plt.xticks(fontsize=font_size) plt.yticks(fontsize=font_size) fig.autofmt_xdate(rotation=0, ha="center") ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["left"].set_visible(False) ax.grid(which="both", axis="y", color="grey", linewidth=grid_line_width, alpha=grid_opacity ) ax.fill_between(x, y1, y, facecolor="#ff8400", alpha=0.25) ax.fill_between(x, 0, y1, facecolor="#EA2027", alpha=0.25) title_font = FontProperties() title_font.set_family("sans-serif") title_font.set_file("./Whitney-Font/whitney-semibold.otf") title_font.set_size(14) title_pad = 18 ax.legend(["Total", "Deaths"], prop={"size": legend_size}, fancybox=True, facecolor="0.25") if graph_type == "linear": ax.set_title(f"Linear graph", pad=title_pad, fontproperties=title_font) plt.yscale("linear") elif graph_type == "log": ax.set_title(f"Logarithmic graph", pad=title_pad, fontproperties=title_font) plt.yscale("log") plt.ylim(bottom=y_limit) plt.minorticks_off() ax.yaxis.set_major_formatter(ticker.FuncFormatter(format_values)) plt.savefig(f"{filename}.png", transparent=True) # plt.show() fig.clear() plt.close(fig)