def create_story(df: pd.DataFrame): #df = df[df['Ascent Type'] == 'Onsight'][df['Style'] == 'Trad'].sort_values('Ascent Date') df = df.sort_values('Ascent Date') fig = plt.figure(figsize=(14, 9)) ax = fig.add_subplot(1, 1, 1) major_ticks = np.arange(0, 26) ax.set_yticks(major_ticks) ax.set_xticks(major_ticks) ax.set_xlim(left=0, right=20) ax.set_ylim(bottom=0, top=20) ax.set_ylabel('Grade') ax.set_xlabel('Count') #counts = get_ascent_counts(df.iloc[:3]) counts = get_ascent_counts(df.iloc[:0]) sum_ = copy.copy(counts['trad_onsights']) trad_onsights_barh = plt.barh(range(1, 25), counts['trad_onsights'], color='green', label='Trad onsight') sport_onsights_barh = plt.barh(range(1, 25), counts['sport_onsights'], left=sum_, color='#98ff98', label='Sport onsight') sum_ += counts['sport_onsights'] trad_flashes_barh = plt.barh(range(1, 25), counts['trad_flashes'], left=sum_, color='#800020', label='Trad flash') sum_ += counts['trad_flashes'] #plt.barh(range(1, 25), sport_flashes, left = trad_onsights + sport_onsights + trad_flashes, color='orange') trad_redpoints_barh = plt.barh(range(1, 25), counts['trad_redpoints'], left=sum_, color='red', label='Trad redpoint') sum_ += counts['trad_redpoints'] #plt.barh(range(1, 25), sport_redpoints, left = trad_onsights + sport_onsights + trad_flashes + sport_flashes + trad_redpoints, color='#FF00FF') pinkpoints_barh = plt.barh(range(1, 25), counts['pinkpoints'], left=sum_, color='pink', label='Pinkpoint (sport or trad)') sum_ += counts['pinkpoints'] cleans_barh = plt.barh(range(1, 25), counts['cleans'], left=sum_, color='xkcd:sky blue', label='Clean lead (yoyo, simulclimbing)') sum_ += counts['cleans'] clean_seconds_barh = plt.barh(range(1, 25), counts['clean_seconds'], left=sum_, color='#FFA500', label='Clean second') sum_ += counts['clean_seconds'] clean_topropes_barh = plt.barh(range(1, 25), counts['clean_topropes'], left=sum_, color='#FFFF00', label='Clean toprope') sum_ += counts['clean_topropes'] battle_to_top_barh = plt.barh( range(1, 25), counts['battle_to_top'], left=sum_, color='gray', label='Battle to top (hangdog, second/toprope weighting rope)') import matplotlib.image as mpimg from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox from scipy import ndimage artists = [] photo = mpimg.imread('animation/photos/20210704_160700.jpg') photo = ndimage.rotate(photo, -90) imagebox = OffsetImage(photo, zoom=0.1) ab = AnnotationBbox(imagebox, (8, 7)) photo_map = { 'Start': mpimg.imread('animation/photos/20210509_092007.jpg'), 'Cloaca': ndimage.rotate(mpimg.imread('animation/photos/20210511_131111.jpg'), -90), 'ScarIet Sage': mpimg.imread('animation/photos/scarlet_sage.png'), 'Diapason': ndimage.rotate(mpimg.imread('animation/photos/20210511_155128.jpg'), -90), 'Diapason2': mpimg.imread('animation/photos/20210511_155129.jpg'), 'Tiptoe Ridge': ndimage.rotate(mpimg.imread('animation/photos/20210512_090702.jpg'), -90), 'Piccolo': ndimage.rotate(mpimg.imread('animation/photos/20210513_113415.jpg'), -90), 'Piccolo2': mpimg.imread('animation/photos/20210513_113643.jpg'), 'Mantle': ndimage.rotate(mpimg.imread('animation/photos/20210704_133931.jpg'), -90), 'Mantle2': mpimg.imread('animation/photos/20210704_160639(0).jpg'), 'Mantle3': mpimg.imread('animation/photos/20210704_160700.jpg') } df['photo'] = df.apply(lambda x: photo_map[x['Ascent Label']] if x['Ascent Label'] in photo_map else None, axis=1) """ artists.append([ab]) #photo = mpimg.imread('animation/photos/20210511_131111.jpg') #photo = ndimage.rotate(photo, -90) #imagebox = OffsetImage(photo, zoom=0.1) #ab = AnnotationBbox(imagebox, (8, 7)) #artists.append([ab]) #ax.add_artist(ab) #ax.imshow(photo) ax2 = fig.add_axes([0.3, 0.2, 0.7, 0.3]) ims = [] im = ax2.imshow(photo) ims.append([im]) photo = mpimg.imread('animation/photos/20210511_131111.jpg') photo = ndimage.rotate(photo, -90) im = ax2.imshow(photo, animated=True) ims.append([im]) print(ims) ani = animation.ArtistAnimation(fig, ims, interval=1000, blit=True) """ #width, height = photo.shape[0], photo.shape[1] #ax2 = fig.add_axes([0.4, 0.4, 0.00010*width, 0.00010*height]) #ax2.tick_params(left=False, # bottom=False) #ax2.set(xticklabels=[], yticklabels=[]) #ax2.imshow(photo, aspect='auto') photo = photo_map['Start'] width, height = photo.shape[0], photo.shape[1] ax3 = fig.add_axes([0.4, 0.2, 0.00016 * height, 0.00016 * width]) ax3.tick_params(left=False, bottom=False) ax3.set(xticklabels=[], yticklabels=[]) ax3.axis('off') ax3.imshow(photo) _ = ax.legend( [clean_seconds_barh, clean_topropes_barh, battle_to_top_barh], ['clean seconds', 'clean topropes', 'weighted rope'], loc='center', bbox_to_anchor=(0.5, -0.10), shadow=False, ncol=3) def prepare_animation(trad_onsights_barh): def animate(frame_number): photo = df.iloc[frame_number - 1].photo if photo is not None: width, height = photo.shape[0], photo.shape[1] ax3.imshow(photo) print(frame_number) counts = get_ascent_counts(df.iloc[:frame_number]) print(counts) trad_onsights_barh_new = ax.barh(range(1, 25), counts['trad_onsights'], color='green', label='Trad onsight') trad_onsights_barh.patches = trad_onsights_barh_new.patches sum_ = copy.copy(counts['trad_onsights']) sport_onsights_barh_new = ax.barh(range(1, 25), counts['sport_onsights'], left=sum_, color='#98ff98', label='Sport onsight') sport_onsights_barh.patches = sport_onsights_barh_new.patches sum_ += counts['sport_onsights'] trad_flashes_barh_new = ax.barh(range(1, 25), counts['trad_flashes'], left=sum_, color='#800020', label='Trad flash') trad_flashes_barh.patches = trad_flashes_barh_new.patches sum_ += counts['trad_flashes'] #ax.barh_new(range(1, 25), sport_flashes, left = trad_onsights + sport_onsights + trad_flashes, color='orange') trad_redpoints_barh_new = ax.barh(range(1, 25), counts['trad_redpoints'], left=sum_, color='red', label='Trad redpoint') trad_redpoints_barh.patches = trad_redpoints_barh_new.patches sum_ += counts['trad_redpoints'] #ax.barh_new(range(1, 25), sport_redpoints, left = trad_onsights + sport_onsights + trad_flashes + sport_flashes + trad_redpoints, color='#FF00FF') pinkpoints_barh_new = ax.barh(range(1, 25), counts['pinkpoints'], left=sum_, color='pink', label='Pinkpoint (sport or trad)') pinkpoints_barh.patches = pinkpoints_barh_new.patches sum_ += counts['pinkpoints'] cleans_barh_new = ax.barh(range(1, 25), counts['cleans'], left=sum_, color='xkcd:sky blue', label='Clean lead (yoyo, simulclimbing)') cleans_barh.patches = cleans_barh_new.patches sum_ += counts['cleans'] clean_seconds_barh_new = ax.barh(range(1, 25), counts['clean_seconds'], left=sum_, color='#FFA500', label='Clean second') clean_seconds_barh.patches = clean_seconds_barh_new.patches sum_ += counts['clean_seconds'] clean_topropes_barh_new = ax.barh(range(1, 25), counts['clean_topropes'], left=sum_, color='#FFFF00', label='Clean toprope') clean_topropes_barh.patches = clean_topropes_barh_new.patches sum_ += counts['clean_topropes'] battle_to_top_barh_new = ax.barh( range(1, 25), counts['battle_to_top'], left=sum_, color='gray', label='Battle to top (hangdog, second/toprope weighting rope)') battle_to_top_barh.patches = battle_to_top_barh_new.patches if frame_number > 0: ax.set_title(f'{df.iloc[frame_number-1]["Ascent Label"]}', fontsize=40) return animate ani = animation.FuncAnimation(fig, prepare_animation(trad_onsights_barh), len(df) + 1, repeat=False, interval=2500) tag = ani.to_html5_video() with open('tag.html', 'w') as f: print(tag, file=f) plt.show()
def drawboard(board, selection, arrows, ax, sizewin): n = len(board) ax.add_patch( pat.Rectangle((-0.9, -0.9), 11.8, 11.8, facecolor='k', edgecolor='none')) ax.add_patch( pat.Rectangle((-0.5, -0.5), 11, 11, facecolor='#fbf9f4', edgecolor='none')) ax.add_patch(pat.Rectangle((-0.5, -0.5), 1, 1, color='grey')) ax.add_patch(pat.Rectangle((-0.5, 9.5), 1, 1, color='grey')) ax.add_patch(pat.Rectangle((9.5, -0.5), 1, 1, color='grey')) ax.add_patch(pat.Rectangle((9.5, 9.5), 1, 1, color='grey')) ax.add_patch(pat.Rectangle((4.5, 4.5), 1, 1, color='grey')) for i in range(n): ax.plot([-0.5, 10.5], [i - 1 / 2, i - 1 / 2], color='k') ax.plot([i - 1 / 2, i - 1 / 2], [-0.5, 10.5], color='k') for j in range(n): if (board[i][j] == -1): ax.add_patch(pat.Circle((i, j), 0.35, color='k')) if (board[i][j] == 1): ax.add_patch(pat.Circle((i, j), 0.35, color='k')) ax.add_patch(pat.Circle((i, j), 0.28, color='#ffeeb5')) if (board[i][j] == 2): im = plt.imread('img/king.png') oi = OffsetImage(im, zoom=0.085 * sizewin) box = AnnotationBbox(oi, (i, j), frameon=False) ax.add_artist(box) if (board[i][j] == 3): ax.plot([i], [j], marker='x', color='r', markersize=25) ax.plot([i], [j], marker='o', markerfacecolor='none', markeredgecolor='k', markersize=30, markeredgewidth=3) if (board[i][j] == -3): ax.plot([i], [j], marker='x', color='r', markersize=25) ax.plot([i], [j], marker='o', color='k', markersize=30) if (convert_coord_to_nb(selection) != 1000): ax.plot([selection[0] - 0.5, selection[0] + 0.5], [selection[1] - 0.5, selection[1] - 0.5], color='r') ax.plot([selection[0] - 0.5, selection[0] + 0.5], [selection[1] + 0.5, selection[1] + 0.5], color='r') ax.plot([selection[0] - 0.5, selection[0] - 0.5], [selection[1] - 0.5, selection[1] + 0.5], color='r') ax.plot([selection[0] + 0.5, selection[0] + 0.5], [selection[1] - 0.5, selection[1] + 0.5], color='r') for i in range(len(arrows)): if type(arrows[i]) == int: x, y = nb_to_coord(arrows[i]) ax.plot(x, y, marker='^', markeredgecolor='r', markersize=15, markeredgewidth=3, fillstyle='none') if type(arrows[i]) == tuple: x1, y1 = nb_to_coord(arrows[i][0]) x2, y2 = nb_to_coord(arrows[i][1]) l = 0.4 dx = (x2 - x1) * (1 - l / sqrt((x2 - x1)**2 + (y2 - y1)**2)) dy = (y2 - y1) * (1 - l / sqrt((x2 - x1)**2 + (y2 - y1)**2)) ax.arrow(x1, y1, dx * 1, dy * 1, head_width=0.4, head_length=l, fc='r', ec='r', width=0.1, zorder=10) alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'] shift = 1.3 for i in range(len(alpha)): ax.text(i - 0.15, -shift, alpha[i], fontsize=14) ax.text(-shift - 0.1 * (i + 1 >= 10), i - 0.15, i + 1, fontsize=14)
def tsne(x, y, y_pred): X_train = np.asarray(x).astype('float64') # shuffle dataset if 1 == 3: p = np.random.permutation(len(X_train)) X_train = X_train[p] y_train = y[p] num_classes = len(np.unique(y)) labels = np.arange(num_classes) # restrict to a sample because slow mask = np.arange(5000) X_sample = x[mask].squeeze() y_sample = y[mask] y_sample_pred = y_pred[mask] if 1 == 1: print("X_sample: {}".format(X_sample.shape)) print("y_sample: {}".format(y_sample.shape)) print("y_pred: {}".format(y_sample_pred.shape)) # flatten images to (N, D) for feeding to t-SNE X_sample_flat = np.reshape(X_sample, [X_sample.shape[0], -1]) # compute tsne embeddings embeddings = TSNE(n_components=2, init='pca', verbose=2).fit_transform(X_sample_flat) # dump #pickle.dump(embeddings, open(config.data_dir + file_name, "wb")) if 1 == 1: fig = plt.figure() ax = fig.add_subplot(111) colors = cm.Spectral(np.linspace(0, 1, num_classes)) xx = embeddings[:, 0] yy = embeddings[:, 1] # plot the images if 1 == 2: for i, (x, y) in enumerate(zip(xx, yy)): im = OffsetImage(X_sample[i], zoom=0.1, cmap='gray') ab = AnnotationBbox(im, (x, y), xycoords='data', frameon=False) ax.add_artist(ab) ax.update_datalim(np.column_stack([xx, yy])) ax.autoscale() # plot the 2D data points for i in range(num_classes): ax.scatter(xx[y_sample == i], yy[y_sample == i], color=colors[i], label=labels[i], s=10) ax.xaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') plt.legend(loc='best', scatterpoints=1, fontsize=5) plt.savefig('ytsne', format='pdf', dpi=600) plt.show() fig2 = plt.figure() ax2 = fig2.add_subplot(111) colors = cm.Spectral(np.linspace(0, 1, num_classes)) xx = embeddings[:, 0] yy = embeddings[:, 1] for i in range(num_classes): ax2.scatter(xx[y_sample_pred == i], yy[y_sample_pred == i], color=colors[i], label=labels[i], s=10) ax2.xaxis.set_major_formatter(NullFormatter()) ax2.yaxis.set_major_formatter(NullFormatter()) plt.axis('tight') plt.legend(loc='best', scatterpoints=1, fontsize=5) plt.savefig('y_pred_tsne', format='pdf', dpi=600) plt.show()
def frequency_analysis(cluster_setlist, cluster_coordinates, graph_figure, ax, first_handle): #Take from network_analysis cluster_counter = 1 for cluster_list in range( len(cluster_setlist )): #Cluster_setlist is a list of networkx set objects. cluster_members = list( cluster_setlist[cluster_list] ) #Converting from networkx object to list of users within a cluster cluster_text_list = [] cluster_text_split_list = [] cluster_word_list = [] for j in range(len(cluster_members)): text_list = [] text_split_list = [] word_list = [] fname = 'user_timeline_' + cluster_members[ j] + '.jsonl' #Converting username back to .jsonl filename geo_list.append(fname) with open( fname ) as f: #Taking JSON file and appending just the text information for each tweet. for line in f: tweet = json.loads(line) text_list.append( tweet['text']) #Adds all tweets to the text list. for k in range( len(text_list) ): #Splits each tweet by word using space as a delimiter. text_split_list.append(text_list[k].split(" ")) for k in range(len(text_split_list)): #Adds all to single list for l in range(len(text_split_list[k])): word_list.append(text_split_list[k][l]) cluster_text_list.append(text_list) cluster_text_split_list.append(text_split_list) cluster_word_list.append(word_list) cluster_text_list = [ item for sublist in cluster_text_list for item in sublist ] #Making cluster data into a flat list cluster_text_split_list = [ item for sublist in cluster_text_split_list for item in sublist ] cluster_word_list = [ item for sublist in cluster_word_list for item in sublist ] content_word_list = content_filter( cluster_word_list ) #Applying filtering of stopwords to the words in the cluster fdist1 = FreqDist(content_word_list) fdist1_most_common = fdist1.most_common( 50 ) #The N number of most common words most frequently used in a cluster df_unigram = pd.DataFrame(fdist1_most_common, columns=['word', 'frequency']) df_unigram.plot(kind='bar', x='word') print(fdist1_most_common) unigram_distribution_variable = [] for i in range(len(fdist1_most_common)): for j in range(fdist1_most_common[i] [1]): #The number of times it appears. unigram_distribution_variable.append(fdist1_most_common[i][0]) unigram_distribution_variable = ' '.join( unigram_distribution_variable ) #This gives what I'd need -- most frequent unigrams as a long string. script_dir = os.path.dirname(__file__) results_dir = os.path.join(script_dir, '{0}/unigram_data/'.format(first_handle)) sample_file_name = "unigram_{0}.csv".format(cluster_counter) #Check? if not os.path.isdir(results_dir): os.makedirs(results_dir) df_unigram.to_csv(results_dir + sample_file_name) results_dir = os.path.join( script_dir, '{0}/unigram_histograms/'.format(first_handle)) sample_file_name = "unigram_histogram_{0}.png".format(cluster_counter) if not os.path.isdir(results_dir): os.makedirs(results_dir) plt.savefig(results_dir + sample_file_name) ### bigrams = [ b for l in cluster_text_list for b in zip(l.split(" ")[:-1], l.split(" ")[1:]) ] remove_stopword_bigram = [] bigrams_pared = [] bigram_filtered = [] bigram_discard = [] for i in range(len(bigrams)): first_condition = bigrams[i][0] in stopwords second_condition = bigrams[i][1] in stopwords if first_condition or second_condition == True: bigram_discard.append(bigrams[i]) elif ('@' == bigrams[i][0][0]) or ( '@' == bigrams[i][1][0]): #Removing mentions from bigrams bigram_discard.append(bigrams[i]) else: bigram_filtered.append(bigrams[i]) fdist2 = FreqDist(bigram_filtered) fdist2_most_common = fdist2.most_common(50) fdist2_most_common_split = [] for i in range(len(fdist2_most_common)): fdist2_most_common_split.append( (fdist2_most_common[i][0][0], fdist2_most_common[i][0][1], fdist2_most_common[i][1])) bigram_distribution_variable = [] for i in range(len(fdist2_most_common)): for j in range(fdist2_most_common[i][1]): bigram_distribution_variable.append(fdist2_most_common[i][0]) #Would need to do more work for turning into word cloud, not so important at athe moment. results_dir = os.path.join(script_dir, '{0}/bigram_data/'.format(first_handle)) sample_file_name = "bigram_{0}.csv".format(cluster_counter) #Check? if not os.path.isdir(results_dir): os.makedirs(results_dir) df_bigram_split = pd.DataFrame(fdist2_most_common_split, columns=['word1', 'word2', 'frequency']) df_bigram_split.to_csv(results_dir + sample_file_name) df_bigram = pd.DataFrame(fdist2_most_common, columns=['bigram pair', 'frequency']) df_bigram.plot(kind='bar', x='bigram pair') results_dir = os.path.join( script_dir, '{0}/bigram_histograms/'.format(first_handle)) sample_file_name = "bigram_histogram_{0}.png".format(cluster_counter) if not os.path.isdir(results_dir): os.makedirs(results_dir) plt.savefig(results_dir + sample_file_name) ''' This is the section of the program that generates word clouds ''' wordcloud = WordCloud( background_color='white', collocations=False).generate(unigram_distribution_variable) results_dir = os.path.join( script_dir, '{0}/unigram_wordclouds/'.format(first_handle)) sample_file_name = "unigram_wordclouds_{0}.png".format(cluster_counter) if not os.path.isdir(results_dir): os.makedirs(results_dir) wordcloud.to_file(results_dir + sample_file_name) cluster_counter += 1 #plt.show() for i in range(len(cluster_coordinates)): img_orig = mpimg.imread('cluster ' + str(i + 1) + '.png') imagebox_python = OffsetImage( img_orig, zoom=0.425) #Zoom magnifies or shrinks the wordcloud object #imagebox_python.set_zorder(1) #An experimental part of the code for positioning zorder of nodes vs word clouds annotation_box = AnnotationBbox( imagebox_python, (cluster_coordinates[i - len(cluster_coordinates)][0] * 1.45, cluster_coordinates[i - len(cluster_coordinates)][1] * 1.40), frameon=False) print(annotation_box) ''' As explained in the network_analysis.py file, the parameters in the line above control the ratio of positioning the word clouds from the distance between the origin and cluster center. ''' ax.add_artist(annotation_box) ax.set_facecolor( 'none' ) #Syntax related to adding custom .png images to existing matplotlib figures. results_dir = os.path.join( script_dir, '{0}/network_with_wordclouds/'.format(first_handle)) sample_file_name = "network_with_wordclouds.png" if not os.path.isdir(results_dir): os.makedirs(results_dir) graph_figure.savefig(results_dir + sample_file_name) return geo_list
def plot_integrated_recorded_lumi(cumulative=False): properties = filter_run_lumi(parse_file(input_analysis_file)) timestamps = sorted(properties['time']) intg_rec_lumi = [ x for (y, x) in sorted(zip(properties['time'], properties['intg_rec_lumi'])) ] intg_del_lumi = [ x for (y, x) in sorted(zip(properties['time'], properties['intg_del_lumi'])) ] # Convert from (ub)-1 to (pb)-1 intg_rec_lumi = [x * 1e-6 for x in intg_rec_lumi] intg_del_lumi = [x * 1e-6 for x in intg_del_lumi] dates = [datetime.datetime.fromtimestamp(int(time)) for time in timestamps] total_rec_lumi = sum(intg_rec_lumi) total_del_lumi = sum(intg_del_lumi) max_lumi = max(intg_rec_lumi) print "Total Rec. Luminosity: {}".format(total_rec_lumi) print "Total Del. Luminosity: {}".format(total_del_lumi) # print "Max Luminosity: {}".format(max_lumi) # rec = [(36.1 * i) / total_del_lumi for i in intg_rec_lumi] # deli = [(36.1 * i) / total_del_lumi for i in intg_del_lumi] # intg_rec_lumi, intg_del_lumi = rec, deli # dates = [datetime.datetime.fromtimestamp( int(time) ).strftime('%m-%d') for time in timestamps] if cumulative: label = "CMS Recorded: " + str(round(total_rec_lumi, 2)) + " $\mathrm{pb}^{-1}$" else: label = "CMS Recorded, max " + str(round( max_lumi, 2)) + " $\mathrm{pb}^{-1}$/day" print "Min date = ", min(dates) print "Max date = ", max(dates) plt.hist(mpl.dates.date2num(dates), label="Recorded", weights=intg_rec_lumi, lw=8, bins=50, cumulative=cumulative, histtype='step', color='orange') plt.hist(mpl.dates.date2num(dates), label="Delivered", weights=intg_del_lumi, lw=8, bins=50, cumulative=cumulative, histtype='step', color='green') years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%Y-%M') # Format the ticks plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d %b')) # plt.gca().xaxis.set_major_locator(mdates.MonthLocator()) plt.xlabel("Date (2010)", labelpad=25, fontsize=70) plt.gca().ticklabel_format(axis='y', style='sci') if cumulative: plt.ylabel("Integrated Luminosity [A.U.]", labelpad=50, fontsize=70) else: plt.ylabel("Average Luminosity [A.U.]", labelpad=50, fontsize=70) plt.gca().get_yaxis().set_ticks([]) print max(intg_rec_lumi), handles, labels = plt.gca().get_legend_handles_labels() legend = plt.gca().legend(handles[::-1], labels[::-1], bbox_to_anchor=[0.007, 0.99], frameon=False, loc='upper left', fontsize=70) plt.gca().add_artist(legend) plt.gcf().set_size_inches(30, 21.4285714, forward=1) # plt.gca().get_yaxis().get_major_formatter().set_powerlimits((0, 0)) plt.autoscale() if cumulative: plt.ylim(0, 330) else: plt.ylim(0, 55) plt.xlim(datetime.date(2010, 9, 20), datetime.date(2010, 10, 31)) plt.locator_params(axis='x', nbins=5) # months = DayLocator([4, 10, 16, 22, 29]) # months = DayLocator([1, 8, 15, 22, 29]) months = WeekdayLocator(mdates.FR) monthsFmt = DateFormatter("%b '%y") plt.gca().xaxis.set_major_locator(months) # plt.gca().xaxis.set_major_formatter(monthsFmt) # plt.gca().set_xticks(plt.gca().get_xticks()[1:]) plt.tick_params(which='major', width=5, length=25, labelsize=70) plt.tick_params(which='minor', width=3, length=15) # plt.gca().xaxis.set_minor_locator(MultipleLocator(0.02)) if cumulative: plt.gca().yaxis.set_minor_locator(MultipleLocator(10)) else: plt.gca().yaxis.set_minor_locator(MultipleLocator(2)) extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0) outside_text = plt.gca().legend([extra], ["CMS 2010 Open Data"], frameon=0, borderpad=0, fontsize=50, bbox_to_anchor=(1.0, 1.005), loc='lower right') plt.gca().add_artist(outside_text) # plt.xlim() if cumulative: logo = [0.062, 0.985] else: logo = [0.051, 0.978] logo_offset_image = OffsetImage(read_png( get_sample_data("/home/aashish/root/macros/MODAnalyzer/mod_logo.png", asfileobj=False)), zoom=0.25, resample=1, dpi_cor=1) text_box = TextArea("", textprops=dict(color='#444444', fontsize=50, weight='bold')) logo_and_text_box = HPacker(children=[logo_offset_image, text_box], align="center", pad=0, sep=25) anchored_box = AnchoredOffsetbox(loc=2, child=logo_and_text_box, pad=0.8, frameon=False, borderpad=0., bbox_to_anchor=logo, bbox_transform=plt.gcf().transFigure) plt.gca().add_artist(anchored_box) plt.tight_layout() plt.gcf().set_size_inches(30, 24, forward=1) if cumulative: plt.savefig("plots/Version 6/lumi_cumulative.pdf") else: plt.savefig("plots/Version 6/lumi.pdf") plt.clf()
def getImage(path): return OffsetImage(plt.imread(path))
def getImage(path, size): image = Image.open(path) image = image.resize(size) return OffsetImage(image)
lon2 = rr.variables['longitude'][:] lat2 = rr.variables['latitude'][:] lon2,lat2 = np.meshgrid(lon2,lat2) ln2,lt2 = m1(lon2, lat2) m1.contourf(ln2,lt2,h,clevs,cmap=mpl.cm.Reds,vmin=0.99,vmax=1.0,alpha=0.95) rr.close() """ rr = Dataset('/home/evgeny/Hackatlon/MetO-NWS-BIO-dm-PHYT_1567692273372.nc', 'r', format='NETCDF4') # Huon (112,81) Hvom (111,82) v=np.mean(rr.variables['PhytoC'][0],axis=0) lon3 = rr.variables['lon'][:] lat3 = rr.variables['lat'][:] lon3,lat3 = np.meshgrid(lon3,lat3) ln3,lt3 = m1(lon3, lat3) #m1.contourf(ln3,lt3,v,clevs,cmap=mpl.cm.rainbow) #,alpha=0.5) for i in range(2,len(v)-2): for j in range(2,len(v.T)-2): if v[i,j] == np.max(v[i-1:i+2,j-1:j+2]) and type(v[i,j])==np.float64 and v[i,j]>1: print(i,j,v[i,j]) plane1 = np.array(Image.open('/home/evgeny/Hackatlon/fish3.png')) im1 = OffsetImage(plane1, zoom=0.15*v[i,j]*1/50) x0, y0 = m1(lon3[i,j], lat3[i,j]) ab1 = AnnotationBbox(im1, (x0,y0), xycoords='data', frameon=False) m1._check_ax().add_artist(ab1) plt.show()
fig, ax = plt.subplots(figsize=[14, 10]) max_vals = [] [max_vals.append(i['y'].max()) for i in val] if np.max(max_vals) == 0: continue for i in val: plt.semilogy(i['x'], i['y'], linewidth=2, label=i['country']) plt.scatter(i['x'][-1], i['y'].values[-1], s=8, marker='o') if i['country'] == 'United_States_of_America': i['country'] = 'USA' if i['country'] == 'United_Kingdom': i['country'] = 'UK' flags = rona_db.flag_images() image = plt.imread(flags[i['country']]) im = OffsetImage(image, zoom=0.25) ab = AnnotationBbox(im, (i['x'][-1], np.max(i['y'])), xycoords='data', frameon=False) ax.add_artist(ab) #plt.annotate(i['country'], (i['x'][-1], i['y'].max()), xytext=(-30, 10), textcoords='offset pixels', fontsize=14) plt.annotate(f'{val[-1]["x"][-1]}', xy=(0.3, 0.95), xycoords='axes fraction', fontsize=14) plt.ylim([100, 1500000]) plt.xlabel(f'Date') plt.ylabel(f'Cases of COVID-19') plt.xticks([], []) plt.legend(loc='upper left') plt.savefig(f'./animation/{i["x"][-1]}_covid19_case_rates.png', dpi=300)
def dibujar_tablero(x, c, n): # Visualiza un tablero dada una formula f # Input: # - f, una lista de literales # - n, un numero de identificacion del archivo # Output: # - archivo de imagen tablero_n.png # Inicializo el plano que contiene la figura fig, axes = plt.subplots() axes.get_xaxis().set_visible(False) axes.get_yaxis().set_visible(False) # Dibujo el tablero step = 1. / 3 tangulos = [] # Creo los cuadrados en el tablero tangulos.append(patches.Rectangle(\ (0, step), \ step, \ step,\ facecolor='turquoise')\ ) tangulos.append(patches.Rectangle(*[(step, 0), step, step],\ facecolor='turquoise')) tangulos.append(patches.Rectangle(*[(2 * step, step), step, step],\ facecolor='turquoise')) tangulos.append(patches.Rectangle(*[(step, 2 * step), step, step],\ facecolor='turquoise')) tangulos.append(patches.Rectangle(*[(2 * step, 2 * step), step, step],\ facecolor='turquoise')) tangulos.append(patches.Rectangle(*[(0, 2 * step), step, step],\ facecolor='turquoise')) tangulos.append(patches.Rectangle(*[(2 * step, 0), step, step],\ facecolor='turquoise')) tangulos.append(patches.Rectangle(*[(step, step), step, step],\ facecolor='turquoise')) tangulos.append(patches.Rectangle(*[(0, 0), step, step],\ facecolor='turquoise')) # Creo las líneas del tablero for j in range(3): locacion = j * step # Crea linea horizontal en el rectangulo tangulos.append(patches.Rectangle(*[(0, step + locacion), 1, 0.015],\ facecolor='teal')) # Crea linea vertical en el rectangulo tangulos.append(patches.Rectangle(*[(step + locacion, 0), 0.015, 1],\ facecolor='teal')) for t in tangulos: axes.add_patch(t) # Cargando imagen arr_img = plt.imread("X.png", format='png') imagebox = OffsetImage(arr_img, zoom=0.1) imagebox.image.axes = axes arr_img2 = plt.imread("C.png", format='png') imagebox2 = OffsetImage(arr_img2, zoom=0.1) imagebox2.image.axes = axes # Creando las direcciones en la imagen de acuerdo a literal direcciones = {} direcciones[1] = [0.165, 0.835] direcciones[2] = [0.5, 0.835] direcciones[3] = [0.835, 0.835] direcciones[4] = [0.165, 0.5] direcciones[5] = [0.5, 0.5] direcciones[6] = [0.835, 0.5] direcciones[7] = [0.165, 0.165] direcciones[8] = [0.5, 0.165] direcciones[9] = [0.835, 0.165] for l in x: if x[l] != 0: ab = AnnotationBbox(imagebox, direcciones[int(l)], frameon=False) axes.add_artist(ab) for k in c: if c[k] != 0: if c[k] == x[k]: print("imposible ubicar O en la casilla " + str(k) + " pues ya esta ocupada.") else: ab2 = AnnotationBbox(imagebox2, direcciones[int(k)], frameon=False) axes.add_artist(ab2) #plt.show() fig.savefig("tablero_" + str(n) + ".png")
def annotated_plot(self, key, zoom=0.2, rep=0, pad=0, xybox=(0, 50), max_hight=None, fd=None, figposx=None, figposy=None, xlim=None, ylim=None, ylabel=None, n_datapoints=None, add_points=False): pth = self._curr_path + "imgs/" if not os.path.exists(pth): raise VIS_EXCEPTION("No image directory found in path " + pth) imgs = os.listdir(pth) imgs.sort() data = self._curr_data[key][rep] l = len(data) if len(imgs) != l: raise VIS_EXCEPTION( "Number of images must match the number of data points") x = None if n_datapoints is None: x = range(len(data)) else: if n_datapoints < len(data): data = data[:n_datapoints] x = range(n_datapoints) if not fd is None: data = fd(data) #fig, ax = plt.subplots() _, ax = plt.subplots() ax.plot(x, data, linewidth=2.0) if add_points: ax.plot(x, data, "k*", mew=0.5, ms=10) if figposy is None: figposy = data if figposx is None: figposx = x i = 0 for pos in zip(figposx, figposy): imgpth = pth + imgs[i] i += 1 fn = get_sample_data(imgpth, asfileobj=False) arr_img = plt.imread(fn, format='png') im = OffsetImage(arr_img, zoom=zoom) im.image.axes = ax ab = AnnotationBbox( im, pos, xybox=xybox, xycoords='axes fraction', boxcoords="offset points", #pad=pad, arrowprops=dict(arrowstyle="<-")) ax.add_artist(ab) mi = np.min(data) ma = np.max(data) r = ma - mi if not xlim is None: ax.set_xlim(xlim[0], xlim[1]) if not ylim is None: ax.set_ylim(ylim[0], ylim[1]) if ylabel is None: plt.ylabel(key, fontsize=15) else: plt.ylabel(ylabel, fontsize=15) labs = range(len(data)) labs = list(map(lambda x: str(x), labs)) ax.set_xticklabels(labs) plt.xlabel("disturbance level", fontsize=15) plt.xticks(x) plt.show()
def DrawContourfAndLegend(contourf, legend, clipborder, patch, cmap, levels, extend, extents, x, y, z, m): """ :param contourf: :param legend: :param clipborder: :param patch: :param cmap: :param levels: :param extend: :param extents: :param x: :param y: :param z: :param m: :return: """ # 是否绘制色斑图 ------ 色版图、图例、裁切是一体的 xmax = extents.xmax xmin = extents.xmin ymax = extents.ymax ymin = extents.ymin if contourf.contourfvisible: # 绘制色斑图 if legend.micapslegendvalue: CS = m.contourf(x, y, z, cmap=cmap, levels=levels, extend=extend, orientation='vertical') else: CS = m.contourf(x, y, z, # cax=axins, levels=legend.legendvalue, colors=legend.legendcolor, extend=extend, orientation='vertical', hatches=legend.hatches) # 用区域边界裁切色斑图 if clipborder.path is not None and clipborder.using: for collection in CS.collections: collection.set_clip_on(True) collection.set_clip_path(patch) if m is plt: # 插入一个新坐标系 以使图例在绘图区内部显示 ax2 = plt.gca() axins = inset_axes(ax2, width="100%", height="100%", loc=1, borderpad=0) axins.axis('off') axins.margins(0, 0) axins.xaxis.set_ticks_position('bottom') axins.yaxis.set_ticks_position('left') axins.set_xlim(xmin, xmax) axins.set_ylim(ymin, ymax) # 画图例 if legend.islegendpic: # 插入图片 arr_lena = read_png(legend.legendpic) image_box = OffsetImage(arr_lena, zoom=legend.legendopacity) ab = AnnotationBbox(image_box, legend.legendpos, frameon=False) plt.gca().add_artist(ab) else: fmt = None CB = plt.colorbar(CS, cmap='RdBu', anchor=legend.anchor, shrink=legend.shrink, # ticks=ticks, # fraction=0.15, # products.fraction, drawedges=True, # not products.micapslegendvalue, filled=False, spacing='uniform', use_gridspec=False, orientation=legend.orientation, # extendfrac='auto', format=fmt ) else: CB = m.colorbar(CS, location=legend.location, size=legend.size, pad=legend.pad ) if CB is not None: fp = Map.GetFontProperties(legend.font) fp_title = Map.GetFontProperties(legend.titlefont) CB.set_label(legend.title, fontproperties=fp_title, color=legend.titlefont['color']) ylab = CB.ax.yaxis.get_label() ylab.set_rotation(legend.titlepos['rotation']) ylab.set_va(legend.titlepos['va']) ylab.set_ha(legend.titlepos['ha']) ylab.set_y(legend.titlepos['ypercent']) if not legend.micapslegendvalue and legend.legendvaluealias: legendvalue = [v for i, v in enumerate(legend.legendvalue) if i % legend.thinning == 0] legendvaluealias = [v for i, v in enumerate(legend.legendvaluealias) if i % legend.thinning == 0] CB.set_ticks(legendvalue, update_ticks=True) CB.set_ticklabels(legendvaluealias, update_ticks=True) CB.ax.tick_params(axis='y', direction='in', length=0) for label in CB.ax.xaxis.get_ticklabels() + CB.ax.yaxis.get_ticklabels(): label.set_color(legend.font['color']) label.set_fontproperties(fp)
def EPL_imscatter(x, y, teams, season='1718', ax=None, zoom=0.25, alpha=0.9): if not ax: fig, ax = plt.subplots() images = read_EPL_images(season=season) icons = [OffsetImage(images[t], zoom=zoom, alpha=alpha) for t in teams] imscatter(x, y, icons, ax=ax)
def getImage(path): return OffsetImage(plt.imread(path), zoom=.33)
## Preparing plots print "Preparing plots \n" f = pl.figure( figsize=(8,5) ) canvas_width, canvas_height = f.canvas.get_width_height() gs = gridspec.GridSpec(2,3) ax0 = pl.subplot(gs[:,:-1]) ## Adding honey comb fn = "hive.png" arr_img = pl.imread(fn, format='png') imagebox = OffsetImage(arr_img, zoom=0.3) imagebox.image.axes = ax0 xy = (250, 260) ab = AnnotationBbox(imagebox, xy, xybox=(0., 0.), xycoords='data', boxcoords="offset points", frameon=False ) ax0.add_artist(ab) hlA, = ax0.plot([], [], 'o', markersize = 3,color=(0.3,1.0,0.3), markeredgecolor=(0.3,1.0,0.3), zorder=0) hl0, = ax0.plot([], [], 's', markersize = 3, color=(1.0,0.2,0.2),
x.append(punktyTygrysy[anim_frames[j]][0]) y.append(punktyTygrysy[anim_frames[j]][1]) else: x.pop() y.pop() line.set_data(x, y) return line, #Wczytywanie obrazu tygrys_obraz = Image.open('tygrysek.png') imageWidth, imageHeight = tygrys_obraz.size print(imageWidth) print(imageHeight) zoomVal = 1 imagebox = OffsetImage(tygrys_obraz, zoom=zoomVal) imageWidth *= zoomVal * 2 imageHeight *= zoomVal * 2 #Losowanie punktów ilosc_tygrysow = 10 maxX = 1000.0 maxY = 1000.0 x = (maxX - imageWidth) * np.random.rand(ilosc_tygrysow) y = (maxY - imageHeight) * np.random.rand(ilosc_tygrysow) #Tworzenie listy klasy Tiger tigerList = [] for i in range(0, ilosc_tygrysow, 1): tigerList.append(Tiger(i, x[i], y[i], imageHeight, imageWidth))
'xticks': (), 'yticks': () }) for i, (component, ax) in enumerate(zip(pca.components_, axes.ravel())): ax.imshow(component.reshape(image_shape), cmap='viridis') ax.set_title("주성분 {} ".format((i + 1))) # %% from matplotlib.offsetbox import OffsetImage, AnnotationBbox image_shape = people.images[0].shape plt.figure(figsize=(20, 3)) ax = plt.gca() imagebox = OffsetImage(people.images[0], zoom=2, cmap="gray") ab = AnnotationBbox(imagebox, (.05, 0.4), pad=0.0, xycoords='data') ax.add_artist(ab) for i in range(4): imagebox = OffsetImage(pca.components_[i].reshape(image_shape), zoom=2, cmap="viridis") ab = AnnotationBbox(imagebox, (.285 + .2 * i, 0.4), pad=0.0, xycoords='data') ax.add_artist(ab) if i == 0: plt.text(.155, .3, 'x_{} *'.format(i), fontdict={'fontsize': 30})
def air_yard_density_viz(df, *team_filter, x_size=30, y_size=35, team_logo=True, save=True): if team_filter: team_list = [team for team in team_filter] df = df.loc[df['posteam'].isin(team_list)].copy() fig, axs = plt.subplots(2, 6, sharey=True, figsize=(x_size,y_size)) else: df = df.copy() fig, axs = plt.subplots(5, 6, sharey=True, figsize=(x_size,y_size)) ay_max = 40 ay_min = -10 axs_list = [item for sublist in axs for item in sublist] axs_list_count = len(axs_list) ordered_groups = (df.groupby(['receiver', 'posteam']).sum() .sort_values('air_yards', ascending=False).iloc[:axs_list_count].index ) grouped = df.groupby(['receiver', 'posteam']) for group_name in ordered_groups: ax = axs_list.pop(0) selection = grouped.get_group(group_name) player = group_name[0] team_color = selection['colors'].max() sns.kdeplot(selection['air_yards'], ax=ax, color=team_color, linewidth=3.0) #shading line = ax.lines[0] x = line.get_xydata()[:,0] y = line.get_xydata()[:,1] ax.fill_between(x, y, color=team_color, alpha=0.5) #formatting ax.set_title(player, fontsize=20) ax.spines['left'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.tick_params( which='both', bottom=False, left=False, right=False, top=False ) ax.set_xlim((ay_min, ay_max)) ax.grid(linewidth=0.25) ax.get_legend().remove() ax.xaxis.set_major_locator(plt.MaxNLocator(3)) ax.yaxis.set_major_locator(plt.MaxNLocator(6)) y_labels = ['{:.2f}'.format(x) for x in ax.get_yticks()] ax.set_yticklabels(y_labels) if team_logo: logo_path = selection['logo'].max() image = OffsetImage(plt.imread(logo_path), zoom=.2) ax.add_artist(AnnotationBbox(image, xy=(0.9,.9), frameon=False, xycoords='axes fraction')) for ax in axs_list: ax.remove() #labels and footnotes year = df['year'].max() week = df['week'].max() fig.suptitle(f'{year} Top {axs_list_count} Players By Total Air Yards through Week {week}', fontsize=30, fontweight='bold', y=1.02) plt.figtext(0.97, -0.01, 'Data: @NFLfastR\nViz: @MulliganRob', fontsize=14) plt.figtext(0.5, -0.01, 'Air Yards', fontsize=20) plt.figtext(-0.01, 0.5, 'Density', fontsize=20, rotation='vertical') fig.tight_layout() if save: if team_filter: team_str = ('_').join(team_filter) fig.savefig(path.join(FIGURE_DIR,f'{year}_Air_Yard_Density_Through{week}_{team_str}.png'), bbox_inches='tight') else: fig.savefig(path.join(FIGURE_DIR,f'{year}_Air_Yard_Density_Through{week}.png'), bbox_inches='tight')
annot.set_visible(True) fig.canvas.draw_idle() else: if vis: annot.set_visible(False) fig.canvas.draw_idle() if __name__ == '__main__': sample = NodeList("rec.json", str(sys.argv[1]) + '.') sample.initializeList() rose = sample.getCoordinates() sample.create_Nodes(sample.data) sns.set(style="white") clientImage = OffsetImage(plt.imread('host.png'), zoom=0.10) serverImage = OffsetImage(plt.imread('server.png'), zoom=0.10) greyImage = OffsetImage(plt.imread('grey.png'), zoom=0.10) x = sample.getNodeIds() y = sample.getAddress() fig, ax = plt.subplots(figsize=(9, 6)) sc = plt.scatter(x, y, marker="s", color='#FFFFFF', s=2000) props = dict(boxstyle='round', facecolor='white', alpha=1.0) annot = ax.annotate("", xy=(0, 0), xytext=(20, 20), textcoords="offset points", bbox=props, arrowprops=dict(arrowstyle="->"))
def scatter_im( X, imfunc, zoom=1, dims_to_plot=[0, 1], ax=None, inset=False, inset_offset=0.15, inset_width_and_height=0.1, plot_range=[0.05, 99.95], inset_colors=None, inset_scatter_size=25, inset_title=None, inset_clims=None, ): # Adapted from https://stackoverflow.com/questions/22566284/matplotlib-how-to-plot-images-instead-of-points/53851017 if ax is None: ax = plt.gca() artists = [] for i in range(X.shape[0]): im = OffsetImage(imfunc(i), zoom=zoom) ab = AnnotationBbox( im, (X[i, dims_to_plot[0]], X[i, dims_to_plot[1]]), xycoords="data", frameon=False, ) artists.append(ax.add_artist(ab)) ax.update_datalim(X[:, dims_to_plot]) ax.autoscale() ax.xaxis.set_ticks_position("none") ax.yaxis.set_ticks_position("none") x_lb, x_hb = np.percentile(X[:, dims_to_plot[0]], plot_range) y_lb, y_hb = np.percentile(X[:, dims_to_plot[1]], plot_range) x_pad = (x_hb - x_lb) * 0.1 y_pad = (y_hb - y_lb) * 0.1 ax.set_xlim(x_lb - x_pad, x_hb + x_pad) ax.set_ylim(y_lb - y_pad, y_hb + y_pad) ax.set_facecolor((0, 0, 0)) nullfmt = NullFormatter() ax.xaxis.set_major_formatter(nullfmt) ax.yaxis.set_major_formatter(nullfmt) ax.axis("off") ax_inset = None if inset: offset = 0.15 inset = [ offset, 1 - inset_offset - inset_width_and_height, inset_width_and_height, inset_width_and_height, ] ax_inset = plt.axes(inset) if inset_clims is None and (not isinstance(inset_colors, str)): inset_clims = np.percentile(inset_colors, [0, 100]) ax_inset.scatter( X[:, dims_to_plot[0]], X[:, dims_to_plot[1]], s=inset_scatter_size, c=inset_colors, vmin=inset_clims[0], vmax=inset_clims[1], ) for k in ax_inset.spines: ax_inset.spines[k].set_color("w") # ax_inset.set_facecolor('w') ax_inset.xaxis.label.set_color("w") ax_inset.yaxis.label.set_color("w") ax_inset.tick_params(axis="x", colors="w") ax_inset.tick_params(axis="y", colors="w") if inset_title is not None: ax_inset.set_title(inset_title) return ax, ax_inset plt.sca(ax) return ax
def visualize_deployment(files, objects, plot_dir, thumbnail): # TODO: Remove magic value of 20 (to compensate for startup time.) start = 50 + 20 fps = 15. # end = 114 # Use up and down arrow for hit/miss # settings = {'marker_hit': 6, 'marker_miss': 7, 'y_hit_m': .08, 'y_hit_c': .015, 'y_miss_c': .015, 'line': True} # settings = {'marker_hit': '^', 'marker_miss': 'v', 'y_hit_m': .08, 'y_hit_c': .015, 'line': True} settings = {'marker_hit': u'$\u2191$', 'marker_miss': 'v', 'y_hit_m': .08, 'y_hit_c': -.008 + .003, 'y_miss_c': .015 - .003, 'line': True} # settings = {'marker_hit': u'$\u2191$', 'marker_miss': u'$\u2193$', 'y_hit_m': .08, 'y_hit_c': -.008, 'y_miss_c': .016, 'line': True} # settings = {'marker_hit': '.', 'marker_miss': 'x', 'y_hit_m': .08, 'y_hit_c': .03, 'line': False} _, ax = plt.subplots(1) for i, (csv_file, obj) in enumerate(zip(files, objects)): xs1 = [] xs2 = [] ys1 = [] ys2 = [] with open(csv_file) as f: for line in f: vals = line.split(',') frame_id = int(vals[0]) is_analyzed = int(vals[1]) if is_analyzed == -1 or frame_id <= start: continue if is_analyzed == 1: xs1.append((frame_id - start) / fps) ys1.append(i * settings['y_hit_m'] + settings['y_hit_c']) else: xs2.append((frame_id - start) / fps) ys2.append(i * settings['y_hit_m'] + settings['y_miss_c']) plt.scatter(xs1, ys1, label=obj["label"] + " hit", color=obj["color"], s=70, marker=settings['marker_hit']) plt.scatter(xs2, ys2, label=obj["label"] + " miss", color=obj["color"], s=70, marker=settings['marker_miss']), if settings['line']: plt.axhline(y=i * settings['y_hit_m'] + 0.003, linestyle="--", color=obj["color"]) picture_loc = (104 - start) / float(fps) train_front = (114 - start) / float(fps) plt.axvline(x=train_front, linestyle="--", color="black", alpha=0.8) plot_file = plot_dir + "/deploy-time-series.pdf" # plt.title("Train detector with 9 concurrent apps", fontsize=20) plt.annotate("Smoke stack\nleaves view", xy=(train_front, -.095), xytext=(20, 12), xycoords='data', fontsize=20, textcoords='offset points', arrowprops=dict(arrowstyle="->")) im = Image.open(thumbnail) im.thumbnail((185, 185)) imagebox = OffsetImage(im) imagebox.image.axes = ax ab = AnnotationBbox(imagebox, (picture_loc, settings['y_hit_m'] + settings['y_hit_c'] - .004), xybox=(-30, -160), xycoords='data', boxcoords='offset points', pad=0, frameon=False, arrowprops=dict(arrowstyle='->')) ax.add_artist(ab) # plt.figimage(im, xo=picture_loc * 72 - 150, yo=83 - 58, zorder=1) plt.xlim(0, max(xs1)) plt.ylim(-.3, .15) plt.xlabel(u"Time elapsed (s)", fontsize=sizes['label']) plt.xticks() plt.tick_params(axis='y', which='major', labelsize=28) plt.tick_params(axis='y', which='minor', labelsize=20) plt.tick_params(axis='x', which='major', labelsize=35) plt.tick_params(axis='x', which='minor', labelsize=30) plt.tick_params(axis='y', which='both', left='off', top='off', labelleft='off') # Fix legend order to match line appearance order handles, labels = ax.get_legend_handles_labels() plt.legend(handles[::-1], labels[::-1], loc=4, fontsize=sizes['legend'], ncol=1, frameon=False) plt.tight_layout() plt.savefig(plot_file) plt.clf()
color='#ffffff') plt.annotate(SkillsDesc, (.7, .43), weight='regular', fontsize=10, color='#ffffff') # plt.annotate(ExtrasTitle, (.7,.43), weight='bold', fontsize=10, color='#ffffff') plt.annotate(ExtrasDesc, (.7, .305), weight='regular', fontsize=10, color='#ffffff') plt.annotate(CodeTitle, (.73, .25), weight='regular', fontsize=10, color='#ffffff') profilepic = mpimage.imread('static/Image/profile.png') profilebox = OffsetImage(profilepic, zoom=0.18) profileab = AnnotationBbox(profilebox, (0.84, 0.8)) ax.add_artist(profileab) qr_code = mpimage.imread('static/Image/myqr.png', 0) imagebox = OffsetImage(qr_code, zoom=0.5) imageqrab = AnnotationBbox(imagebox, (0.84, 0.12)) ax.add_artist(imageqrab) plt.savefig('static/Pdf/resumefrompython_pdf.pdf', dpi=300, bbox_inches='tight') plt.savefig('static/Pdf/resumefrompython_png.png', dpi=300, bbox_inches='tight')
def plot_neighbors_soft_hist(raw_dirpath, tile_info_list, output_dirname, fig_name): patch_info_list = get_patch_info_list(tile_info_list, output_dirname) neighbors_soft_array = np.empty(len(patch_info_list)) for i, patch_info in enumerate( tqdm(patch_info_list, desc="Reading neighbors_soft: ")): # additional_args = { # "overwrite_polygon_dir_name": POLYGON_DIRNAME, # } # image, metadata, polygons = read.load_gt_data(raw_dirpath, tile_info["city"], tile_info["number"], # additional_args=additional_args) # scaled_bbox = np.array(bbox / scale_factor, dtype=np.int) # p_image = image[scaled_bbox[0]:scaled_bbox[2], scaled_bbox[1]:scaled_bbox[3], :] # p_polygons = polygon_utils.crop_polygons_to_patch_if_touch(polygons, scaled_bbox) tile_name = read.IMAGE_NAME_FORMAT.format(city=patch_info["city"], number=patch_info["number"]) bbox = patch_info["bbox"] neighbors_soft_filepath = OUTPUT_FILEPATH_FORMAT.format( dir="similarity_stats", fold=patch_info["fold"], out_dir=output_dirname, tile=tile_name, b0=bbox[0], b1=bbox[1], b2=bbox[2], b3=bbox[3], out_name="neighbors_soft", ext="npy") neighbors_soft = np.load(neighbors_soft_filepath) neighbors_soft_array[i] = neighbors_soft # Sort patch_data_list # patch_data_list = sorted(patch_data_list, key=lambda patch_data: patch_data["neighbors_soft"]) # Compute histogram: hist, bin_edges = np.histogram(neighbors_soft_array) freq = hist / np.sum(hist) # Find patches closest to bin_edges[1:] selected_index_list = [ netsimilarity_utils.get_nearest_to_value(neighbors_soft_array, bin_edge) for bin_edge in bin_edges[1:] ] # Save closest_index_list np.save("{}.bin_index_list.npy".format(output_dirname), selected_index_list) # Load images and polygons selected_patch_info_list = [ patch_info_list[i] for i in selected_index_list ] selected_images, selected_polygons = load_data(raw_dirpath, selected_patch_info_list) # Plot f = plt.figure(figsize=(26, 13)) f.set_tight_layout({"pad": .0}) ax = f.gca() plt.bar(bin_edges[1:], freq, width=np.diff(bin_edges), align="edge") bin_x_half_width = np.diff(bin_edges) / 2 bin_x_center = bin_edges[1:] + bin_x_half_width bin_x_right = bin_x_center + 0.8 * bin_x_half_width bin_y = freq zoom = 0.3 for x_center, x_right, y, image, polygons in zip(bin_x_center, bin_x_right, bin_y, selected_images, selected_polygons): im_polygons = polygon_utils.draw_polygons(polygons, image.shape, fill=False, edges=True, vertices=False, line_width=5) im_polygons_mask = 0 < im_polygons[..., 0] im_display = image im_display[im_polygons_mask] = (255, 0, 0) im = OffsetImage(im_display, zoom=zoom) ab = AnnotationBbox(im, (x_center, y + 0.065), xycoords='data', frameon=False) ax.text(x_right, y + 0.01, u'\u2191', fontname='STIXGeneral', size=30, va='center', ha='center', clip_on=True) ax.add_artist(ab) ax.set_ylim([0, 0.55]) ax.set_xlabel("Neighbors soft", fontsize=20) ax.set_ylabel("Frequency", fontsize=20) plt.savefig(fig_name + ".eps", dpi=300) plt.show()
def generate_auc_figures(bm_csv_dir, png_dir, error_bands=False, format_maintext=False): """ Generate figures for fragment recovery benchmark :param df: :return: """ global fraction fraction_recovery_list = [] annotation_x_positions = (0.3, 0.3, 0.3, 0.3, 0.3) if format_maintext else (0.3, 0.3, 0.3, 0.2, 0.2) annotation_y_positions = (0.33, 0.26, 0.19, 0.12, 0.05) if format_maintext else (0.3, 0.25, 0.2, 0.15, 0.1, 0.05) annotation_fontsize = 16 if format_maintext else 10 for csv in os.listdir(bm_csv_dir): if csv.endswith('.csv'): df = pd.read_csv(os.path.join(bm_csv_dir, csv)) for fragment, fragment_df in df.groupby('fragment'): print(fragment) fig = plt.figure() plt.rcParams.update({'font.size': annotation_fontsize}) if error_bands: muh_plot = sns.lineplot(x='fraction', y='recovered', data=fragment_df, ci='sd', err_style='band', estimator=np.mean) sns.regplot(x='fraction', y='recovered', data=fragment_df, x_estimator=np.mean, x_ci=None, fit_reg=False, ax=muh_plot, scatter_kws={'color': list(sns.color_palette("Blues_r")[1])}) else: muh_plot = sns.regplot(x='fraction', y='recovered', data=fragment_df, x_ci='sd', x_estimator=np.mean, fit_reg=False) # Format axes for main text/suppmat if format_maintext: muh_plot.tick_params(labelsize=16, labelrotation=45) muh_plot.set(ylim=(0, 1.1)) muh_plot.set(xlim=(0, 1.1)) muh_plot.set_xlabel('PDB Fraction') muh_plot.set_ylabel('Clusters Recovered') # Fraction of PDB for 80% recovery for fraction, fraction_df in fragment_df.groupby('fraction'): avg_recovered = fraction_df['recovered'].mean() if avg_recovered > 0.8: break fraction_recovery_list.append({'fraction': fraction, 'fragment': fragment}) # AUC calculation # auc_info = [(fraction, recovered['recovered'].mean()) for fraction, recovered in fragment_df.groupby('fraction')] # x_coords = [a[0] for a in auc_info] # y_coords = [a[1] for a in auc_info] # muh_plot.text(0.7, 0.05, f'AUC: {np.trapz(y_coords, x_coords):.4f}') # embed fragment RDKit image if not format_maintext: fragment_png = mpimg.imread(os.path.join(png_dir, f'{fragment}.png')) fragment_inlay = OffsetImage(fragment_png, zoom=0.15) ab = AnnotationBbox(fragment_inlay, (0.915, 0.25), pad=0) muh_plot.add_artist(ab) # Add annotations # if not format_maintext: # muh_plot.text(annotation_x_positions[0], annotation_y_positions[0], f'{fragment}') muh_plot.text(annotation_x_positions[1], annotation_y_positions[1], f'Total Residues: {fragment_df["total_residues"].median():.0f}') muh_plot.text(annotation_x_positions[2], annotation_y_positions[2], f'Total Clusters: {fragment_df["total_clusters"].median():.0f}') muh_plot.text(annotation_x_positions[3], annotation_y_positions[3], f'Fraction PDB sampled for') muh_plot.text(annotation_x_positions[4], annotation_y_positions[4], f'>80% contact recovery: {fraction:.2f}') if format_maintext: muh_plot.tick_params(labelsize=16) fig.add_axes(muh_plot) figure_name = f'{fragment}-cluster_recovery-{"band" if error_bands else "bars"}.png' fig.savefig(figure_name, dpi=600, bbox_inches='tight', transparent=True) plt.close() # Fraction recovered Histogram df = pd.DataFrame(fraction_recovery_list) sns.set(style="whitegrid", palette="hls") sns.set_context("paper", font_scale=1.5) fig, ax = plt.subplots(figsize=(6,6)) sns.countplot(df['fraction'].round(2), color='#007CBE', ax=ax) fig.suptitle('Fraction of PDB Required for >80%\nContact Recovery Across All Tested Fragments') ax.set_xlabel('Fraction', fontsize=12) ax.set_ylabel('Count', fontsize=12) fig.savefig('RecoveryHist.tiff', dpi=300) df.to_csv('FractionRecovered.csv')
def plot_inst_lumi(): properties = parse_file(input_analysis_file) timestamps = sorted(properties['time']) inst_lumi = [ x for (y, x) in sorted(zip(properties['time'], properties['avg_inst_lumi'])) ] max_lumi = max(inst_lumi) print "Max Inst Luminosity: {}".format(max_lumi) inst_lumi = [x * 1e-3 for x in inst_lumi] dates = [datetime.datetime.fromtimestamp(int(time)) for time in timestamps] # dates = [datetime.datetime.fromtimestamp( int(time) ).strftime('%m-%d') for time in timestamps] label = "Max. Inst. Lumi.: " + str(round(max_lumi, 2)) + " Hz/$\mathrm{\mu b}$" plt.hist(mpl.dates.date2num(dates), label=label, weights=inst_lumi, bins=25, color='orange', edgecolor='darkorange') years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%Y-%M') # format the ticks plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d %b')) plt.gca().xaxis.set_major_locator(mdates.MonthLocator()) plt.xlabel("Date (UTC)", labelpad=40, fontsize=60) plt.ylabel("Peak Delivered Luminosity (Hz/$\mathrm{\mu b}$)", labelpad=50, fontsize=60) plt.legend(bbox_to_anchor=[0.007, 0.85], frameon=False, loc='upper left', fontsize=50) plt.gcf().set_size_inches(30, 21.4285714, forward=1) plt.gcf().autofmt_xdate() plt.autoscale() plt.xlim(datetime.date(2010, 3, 30), datetime.date(2010, 10, 31)) # plt.gca().xaxis.set_minor_locator(MultipleLocator(0.02)) extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0) outside_text = plt.gca().legend([extra], ["CMS 2010 Open Data"], frameon=0, borderpad=0, fontsize=50, bbox_to_anchor=(1.0, 1.005), loc='lower right') plt.gca().add_artist(outside_text) plt.tick_params(which='major', width=5, length=15, labelsize=60) ab = AnnotationBbox(OffsetImage(read_png( get_sample_data("/home/aashish/root/macros/MODAnalyzer/mod_logo.png", asfileobj=False)), zoom=0.15, resample=1, dpi_cor=1), (0.205, 0.840), xycoords='figure fraction', frameon=0) plt.gca().add_artist(ab) preliminary_text = "Prelim. (20\%)" plt.gcf().text(0.270, 0.825, preliminary_text, fontsize=60, weight='bold', color='#444444', multialignment='center') plt.savefig("plots/Version 6/lumi/inst_lumi_number.pdf") plt.clf()
img_resized = np.zeros(shape=(440, 256, 256, 3)) for i in range(len(img)): img_resized[i] = cv2.resize(img[i], (256, 256), interpolation=cv2.INTER_CUBIC) print("1. Computing random projection") t0 = time() X_projected = random_projection.SparseRandomProjection(n_components=2, random_state=42).fit_transform(x) t1 = time() #print("Computing time is {}s".format(t1-t0)) # Plot and save fig, ax = plt.subplots(figsize=(60,48)) ax.scatter(X_projected[:,0], X_projected[:,1]) for i in range(len(img)): imagebox = OffsetImage(img_resized[i], zoom=0.2) ab = AnnotationBbox(imagebox, (X_projected[i][0],X_projected[i][1]), frameon=False) ax.add_artist(ab) plt.draw() plt.savefig('/home/kdh/Desktop/tensorflow/bhtsne/pic/random_resized.png',bbox_inches='tight') plt.show() print("2. Computing PCA projection") t0 = time() X_pca = decomposition.TruncatedSVD(n_components=2).fit_transform(x) t1 = time() #print("Computing time is {}s".format(t1-t0))
def showtoolbar(ax, sizewin): im = plt.imread('img/toolbar.png') oi = OffsetImage(im, zoom=0.425 * sizewin) box = AnnotationBbox(oi, (0.4, 0.622), frameon=False) ax.add_artist(box)
def show_time_series(self, show_segmentations=False, show=False, save_fig=False): """ @param show_segmentations: whether to show segmentations @type show_segmentations: bool @param show: whether to show image @type show: bool @param save_fig: whether to fave figure @type save_fig: bool @return: None @rtype: """ font = { 'family': 'serif', 'color': 'darkorange', 'weight': 'normal', 'size': 10 } if show_segmentations: seg_cmap, seg_norm, bounds = color_mappings() self.add_segmentation_to_timeline() self.add_oct_to_timeline() plt.style.use('ggplot') darkred_patch = mpatches.Patch(color='darkorange', label='injections') time_series = self.time_series if max(time_series) < 1: y_max = 1 else: y_max = 3 fig, ax = plt.subplots(figsize=(int(time_series.shape[0]), 2)) fig.subplots_adjust(top=0.4) xs = [1, 3, 6, 12] ys = time_series # plot points ax.plot(xs, ys, "bo-") x_offset = 0 xy_box = { 0: (x_offset, y_max // 5), 1: (x_offset, (y_max // 5) * 2), 2: (x_offset, (y_max // 5) * 3) } # zip joins x and y coordinates in pairs for x, y in zip(xs, ys): if not self.time_line[x + 1]['cur_va_rounded'] is np.nan: label = f"Inj: {self.time_line[x + 1]['injections']} \n VA: {self.time_line[x + 1]['cur_va_rounded']}" else: label = "" ax.text(x, y + 0.01, label, fontdict=font) if show_segmentations & (self.time_line[x + 1]["study_date"] is not np.nan): for i in range(MeasureSeqTimeUntilDry.NUM_SEGMENTATIONS): imagebox = OffsetImage( self.time_line[x + 1]["segmentation_maps"][i, :, :], cmap=seg_cmap, norm=seg_norm) imagebox.image.axes = ax ab = AnnotationBbox(imagebox, (x, 0), xybox=(x + xy_box[i][0], 0 - xy_box[i][1]), frameon=False) ax.add_artist(ab) plt.ylim(-y_max, y_max) plt.xlabel("month") plt.ylabel("effect") plt.legend(handles=[darkred_patch]) title_ = f"{self.patient_id}_{self.laterality}" plt.title(title_) if show: plt.show() if save_fig: save_path = os.path.join(WORK_SPACE, "dump") if not os.path.exists(save_path): os.makedirs(save_path, exist_ok=True) ax.figure.savefig(os.path.join(save_path, f"{title_}_timeseries.png"), dpi=ax.figure.dpi) plt.close()
def getImage(path): image = Image.open(path) image = image.resize((128, 128)) #image = ops.invert(image) return OffsetImage(image)
def create_stack_chart(df: pd.DataFrame): """ import numpy as np import pandas as pd from pandas import Series, DataFrame import matplotlib.pyplot as plt data1 = [23,85, 72, 43, 52] data2 = [42, 35, 21, 16, 9] plt.bar(range(len(data1)), data1) plt.bar(range(len(data2)), data2, bottom=data1) plt.show() """ counts = get_ascent_counts(df) fig = plt.figure(figsize=(15, 10)) ax = fig.add_subplot(1, 1, 1) major_ticks = np.arange(0, 26) ax.set_yticks(major_ticks) sum_ = copy.copy(counts['trad_onsights']) plt.barh(range(1, 25), counts['trad_onsights'], color='green', label='Trad onsight') plt.barh(range(1, 25), counts['sport_onsights'], left=sum_, color='#98ff98', label='Sport onsight') sum_ += counts['sport_onsights'] plt.barh(range(1, 25), counts['trad_flashes'], left=sum_, color='#800020', label='Trad flash') sum_ += counts['trad_flashes'] #plt.barh(range(1, 25), sport_flashes, left = trad_onsights + sport_onsights + trad_flashes, color='orange') plt.barh(range(1, 25), counts['trad_redpoints'], left=sum_, color='red', label='Trad redpoint') sum_ += counts['trad_redpoints'] #plt.barh(range(1, 25), sport_redpoints, left = trad_onsights + sport_onsights + trad_flashes + sport_flashes + trad_redpoints, color='#FF00FF') plt.barh(range(1, 25), counts['pinkpoints'], left=sum_, color='pink', label='Pinkpoint (sport or trad)') sum_ += counts['pinkpoints'] plt.barh(range(1, 25), counts['cleans'], left=sum_, color='xkcd:sky blue', label='Clean lead (yoyo, simulclimbing)') sum_ += counts['cleans'] plt.barh(range(1, 25), counts['clean_seconds'], left=sum_, color='#FFA500', label='Clean second') sum_ += counts['clean_seconds'] plt.barh(range(1, 25), counts['clean_topropes'], left=sum_, color='#FFFF00', label='Clean toprope') sum_ += counts['clean_topropes'] plt.barh(range(1, 25), counts['battle_to_top'], left=sum_, color='gray', label='Battle to top (hangdog, second/toprope weighting rope)') _ = ax.legend(loc='center', bbox_to_anchor=(0.5, -0.10), shadow=False, ncol=2) # Insert an image import matplotlib.image as mpimg from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox from scipy import ndimage artists = [] photo = mpimg.imread('animation/photos/20210704_160700.jpg') photo = ndimage.rotate(photo, -90) imagebox = OffsetImage(photo, zoom=0.1) ab = AnnotationBbox(imagebox, (8, 7)) artists.append([ab]) #photo = mpimg.imread('animation/photos/20210511_131111.jpg') #photo = ndimage.rotate(photo, -90) #imagebox = OffsetImage(photo, zoom=0.1) #ab = AnnotationBbox(imagebox, (8, 7)) #artists.append([ab]) #ax.add_artist(ab) #ax.imshow(photo) ax2 = fig.add_axes([0.3, 0.2, 0.7, 0.3]) ims = [] im = ax2.imshow(photo) ims.append([im]) photo = mpimg.imread('animation/photos/20210511_131111.jpg') photo = ndimage.rotate(photo, -90) im = ax2.imshow(photo, animated=True) ims.append([im]) print(ims) ani = animation.ArtistAnimation(fig, ims, interval=3050, blit=True) """ def prep_anim(ab): def animate(frame_number): photo = mpimg.imread('animation/photos/20210511_131111.jpg') photo = ndimage.rotate(photo, -90) imagebox2 = OffsetImage(photo, zoom=0.1) ab.offsetbox = imagebox2 #photo = mpimg.imread('animation/photos/20210511_131111.jpg') #imagebox.set_data(photo) #print(imagebox._data) #print('ok') #imagebox.draw() return ab return animate ani = animation.FuncAnimation(fig, prep_anim(ab), repeat=False, interval=2222, blit=True) """ plt.show()