def ex1(): plt.figure(1) ax = plt.axes([0, 0, 1, 1]) ax.set_yticks([0, 5]) ax.set_yticklabels(["label yang sangat panjang"]) make_axes_area_auto_adjustable(ax)
def draw_count(c, title, fig_name, out_path): categories = c.keys() freq = [max(np.log10(max(c[cat], 0.1)), 0) for cat in categories] if all([isinstance(cat, str) for cat in categories]) or all( [isinstance(cat, tuple) for cat in categories]): categories_rev = [cat[::-1] for cat in categories] categories_rev = [x for _, x in sorted(zip(freq, categories_rev))] freq = sorted(freq) else: # Integers, sort by value categories_rev = [cat for cat in categories] freq = [x for _, x in sorted(zip(categories_rev, freq))] categories_rev = sorted(categories_rev) xticks = np.arange(int(max(freq)) + 1) xtick_labels = [np.power(10, t) for t in xticks] fig, ax = plt.subplots(figsize=(20, 10)) y_pos = np.arange(len(categories)) rects = ax.barh(y_pos, freq, align='center', color='green', ecolor='black') ax.set_yticks(y_pos) ax.set_yticklabels(categories_rev) ax.set_xticks(xticks) ax.set_xticklabels(xtick_labels) ax.set_xlabel('מספר מופעים'[::-1]) ax.set_title(title) make_axes_area_auto_adjustable(ax) autolabel(rects, ax) plt.savefig(out_path + '/' + fig_name + '.pdf') plt.close()
def draw_double_count(c_c, title, fig_name, out_path): n_bins = int(np.floor(np.log2(max(c_c.keys())))) categories = ['1'] + \ [str(int(np.power(2, i + 1))) + '-' + str(int(np.power(2, i + 2)) - 1) for i in range(n_bins - 2)] + \ [str(int(np.power(2, n_bins - 1))) + '+'] # For example categories may be ['1', '2-3', '4-7', '8-15', '16-31', '32-63', '64-127', '128+'] y_pos = np.arange(len(categories)) freq = np.zeros(n_bins) for n in c_c.keys(): b = min(n_bins - 1, int(np.log2(n))) freq[b] += c_c[n] freq = [max(np.log10(max(f, 0.1)), 0) for f in freq] xticks = np.arange(int(max(freq)) + 1) xtick_labels = [np.power(10, t) for t in xticks] fig, ax = plt.subplots(figsize=(20, 10)) rects = ax.barh(y_pos, freq, align='center', color='green', ecolor='black') ax.set_yticks(y_pos) ax.set_yticklabels(categories) ax.set_xticks(xticks) ax.set_xticklabels(xtick_labels) ax.set_xlabel('מספר מופעים'[::-1]) ax.set_title(title) make_axes_area_auto_adjustable(ax) autolabel(rects, ax) plt.savefig(out_path + '/' + fig_name + '.pdf') plt.close()
def graph_term_import(df_row, theme_num, word_qty=50): #INPUT: df_row, a row from the output of pandas_visualization #INPUT: theme_num, the theme number #OUPUT: Horizontal Bar Chart of term import in theme #x is labels, y is values x = [df_row[i * 2 + 1] for i in range(1, word_qty)] y = [ float(df_row[i * 2]) if str(df_row[i * 2]) > '0' else 0 for i in range(1, word_qty) ] x_pos = np.arange(word_qty - 1) ticks_font = font_manager.FontProperties(style='normal', size=7, weight='normal', stretch='normal') fig = plt.figure(figsize=(16, 12)) ax = fig.add_subplot(111) ax.barh(x_pos, y, align='center', alpha=0.4) ax.set_yticks(x_pos) ax.set_yticklabels(x) for label in ax.get_yticklabels(): label.set_fontproperties(ticks_font) ax.set_xlabel('Word Probability') ax.set_ylabel('Terms') ax.set_title('Theme {}'.format(theme_num)) make_axes_area_auto_adjustable(ax) plt.savefig('visualizations/visualization{}.png'.format(theme_num))
def graph_term_import(df_row, theme_num): #INPUT: df_row, a row from the output of pandas_visualization #INPUT: theme_num, the theme number #OUPUT: Horizontal Bar Chart of term import in theme #output is limited to 3 top terms. x = [df_row[i*2] for i in range(0, 3)] y = [float(df_row[i*2+1]) if str(df_row[i*2]) > '0' else 0 for i in range(0, 3)] print y, '\n\n\n' x_pos = np.arange(3) ticks_font = font_manager.FontProperties(family='Helvetica', style='normal', size=16, weight='normal', stretch='normal') fig = plt.figure(figsize = (16,12)) ax = fig.add_subplot(111) ax.barh(x_pos, y, align='center', alpha=0.4) ax.set_yticks(x_pos) ax.set_yticklabels(x) for label in ax.get_yticklabels(): label.set_fontproperties(ticks_font) ax.set_xlabel('Correlation') ax.set_ylabel('Terms') ax.set_title('Theme {}'.format(theme_num)) make_axes_area_auto_adjustable(ax) plt.savefig('visualization{}.png'.format(theme_num))
def ex1(): plt.figure(1) ax = plt.axes([0, 0, 1, 1]) #ax = plt.subplot(111) ax.set_yticks([0.5]) ax.set_yticklabels(["very long label"]) make_axes_area_auto_adjustable(ax)
def ex1(): plt.figure(1) ax = plt.axes([0, 0, 1, 1]) #ax = plt.subplot(111) ax.set_yticks([0.5]) ax.set_yticklabels(["very long label"]) make_axes_area_auto_adjustable(ax)
def test_auto_adjustable(): fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) pad = 0.1 make_axes_area_auto_adjustable(ax, pad=pad) fig.canvas.draw() tbb = ax.get_tightbbox(fig._cachedRenderer) assert tbb.x0 == pytest.approx(pad * fig.dpi) assert tbb.x1 == pytest.approx(fig.bbox.width - pad * fig.dpi) assert tbb.y0 == pytest.approx(pad * fig.dpi) assert tbb.y1 == pytest.approx(fig.bbox.height - pad * fig.dpi)
def ex2(): plt.figure(2) ax1 = plt.axes([0, 0, 1, 0.5]) ax2 = plt.axes([0, 0.5, 1, 0.5]) ax1.set_yticks([0.5]) ax1.set_yticklabels(["label yang sangat panjang"]) ax1.set_ylabel("Y label") ax2.set_title("Judul") make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2]) make_axes_area_auto_adjustable(ax2, pad=0.1, use_axes=[ax1, ax2])
def plotFy(): for i in range(0,nTimesteps,100): fig = plt.figure() ax = plt.axes([0,0,1,1]) ax.set_color_cycle(palettable.colorbrewer.qualitative.Dark2_8.mpl_colors) plt.plot(spanLoc,b1Fy[:,i]) plt.xlabel('Span location (m)') plt.ylabel('Blade 1 - Normal force (N)') make_axes_area_auto_adjustable(ax) plt.savefig('B1Fy_t{}.png'.format(i)) plt.close(fig)
def plotTwoTurbineOutput(d1x,d1y,case1Label,d2x,d2y,case2Label,chanName,chanUnit=''): fig = plt.figure() ax = plt.axes([0,0,1,1]) ax.set_color_cycle(palettable.colorbrewer.qualitative.Dark2_8.mpl_colors) plt.plot(d1x,d1y,label=case1Label) plt.plot(d2x,d2y,label=case2Label) plt.xlabel('Time (s)') plt.ylabel('{} ({})'.format(chanName,chanUnit)) plt.legend(loc=0) make_axes_area_auto_adjustable(ax) plt.savefig('compare{}_{}_{}.png'.format(case1Label,case2Label,chanName)) plt.close(fig)
def ex2(): plt.figure(2) ax1 = plt.axes([0, 0, 1, 0.5]) ax2 = plt.axes([0, 0.5, 1, 0.5]) ax1.set_yticks([0.5]) ax1.set_yticklabels(["very long label"]) ax1.set_ylabel("Y label") ax2.set_title("Title") make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2]) make_axes_area_auto_adjustable(ax2, pad=0.1, use_axes=[ax1, ax2])
def ex2(): plt.figure(2) ax1 = plt.axes([0, 0, 1, 0.5]) ax2 = plt.axes([0, 0.5, 1, 0.5]) ax1.set_yticks([0.5]) ax1.set_yticklabels(["very long label"]) ax1.set_ylabel("Y label") ax2.set_title("Title") make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2]) make_axes_area_auto_adjustable(ax2, pad=0.1, use_axes=[ax1, ax2])
def plot_unit(distribution, plot_dir, plot_extension, unit): fig, axes = plt.subplots(figsize=(6.4, 0.85 + len(distribution) / 2)) axes.set(title=unit, xlabel="aantal studenten", ylabel="vraag") for name, marks in distribution: left = 0 for mark, count in marks: axes.barh(name, count, left=left, color=f"C{round(float(str(mark).replace(',', '.')))}") if int(count) > 0: axes.text(left + int(count) / 2, name, str(mark), verticalalignment="center") left += count make_axes_area_auto_adjustable(axes) filename = os.path.join(plot_dir, f"unit_{unit}.{plot_extension}") fig.savefig(filename) plt.close() return unit, filename
def draw_reference_dist(vals, ax, title): label = 'כל התיקים' col = 'green' freq, rects = draw_durations_dist(vals, ax, label, col) y_pos = np.arange(n_weeks) categories = [7 * (i + 1) for i in range(n_weeks)] ax.set_yticks(y_pos) ax.set_yticklabels([str(int(2 * c / 7)) + 'w' for c in categories]) xticks = np.arange(int(max(freq)) + 1) xtick_labels = [np.power(10, t) for t in xticks] ax.set_xticks(xticks) ax.set_xticklabels(xtick_labels) ax.set_xlabel('מספר תיקים פשוטים לפי משך'[::-1]) ax.set_ylabel('משך'[::-1]) ax.set_title(title[::-1]) make_axes_area_auto_adjustable(ax) draw_utils.autolabel(rects, ax) return freq
def test2_timeseries(self, boreholeno, compound, datefrom, dateto): """ Based of matplotlib.plot_date TEST: Use of ax - one borehole multiple compounds """ # Figure 1 from mpl_toolkits.axes_grid1 import make_axes_locatable from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable plt.figure(1) ax = plt.axes([0, 0, 1, 1]) # ax = plt.subplot(111) ax.set_yticks([0.5]) ax.set_yticklabels(["very long label"]) make_axes_area_auto_adjustable(ax) plt.show() # Figure 2 plt.figure(2) ax1 = plt.axes([0, 0, 1, 0.5]) ax2 = plt.axes([0, 0.5, 1, 0.5]) ax1.set_yticks([0.5]) ax1.set_yticklabels(["very long label"]) ax1.set_ylabel("Y label") ax2.set_title("Title") make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2]) make_axes_area_auto_adjustable(ax2, pad=0.1, use_axes=[ax1, ax2]) # Figure 3 fig = plt.figure(3) ax1 = plt.axes([0, 0, 1, 1]) divider = make_axes_locatable(ax1) ax2 = divider.new_horizontal("100%", pad=0.3, sharey=ax1) ax2.tick_params(labelleft="off") fig.add_axes(ax2) divider.add_auto_adjustable_area(use_axes=[ax1], pad=0.1, adjust_dirs=["left"]) divider.add_auto_adjustable_area(use_axes=[ax2], pad=0.1, adjust_dirs=["right"]) divider.add_auto_adjustable_area(use_axes=[ax1, ax2], pad=0.1, adjust_dirs=["top", "bottom"]) ax1.set_yticks([0.5]) ax1.set_yticklabels(["very long label"]) ax2.set_title("Title") ax2.set_xlabel("X - Label") return True
def plot_kmer_matrix(self, kmer_matrix): interval_size = 1 if len(kmer_matrix) > self.max_kmers_to_show: interval_size = int( math.ceil(len(kmer_matrix) / self.max_kmers_to_show)) base_sample_names = [] common_prefix = os.path.commonprefix(self.assemblies) for assembly in self.assemblies: stripped_assembly = assembly.replace(common_prefix, '').replace( '/filtered_scaffolds.fasta', '') base_sample_names.append(os.path.basename(stripped_assembly)) fig, ax = plt.subplots() ax.matshow(kmer_matrix, cmap=plt.cm.Greys, aspect='auto') plt.ylabel('Samples') plt.xlabel('k-mers') ax.set_yticks(range(len(base_sample_names))) ax.set_yticklabels(base_sample_names) make_axes_area_auto_adjustable(ax) plt.savefig(self.output_filename())
def create_gantt(wps, **config): # plot config width = config.get('barwidth', 0.9) markersize = config.get('markersize', 50) wp_offset = 1 - config.get('id_first_wp', 1) show_delivmile = config.get('show_delivmile', True) collapse_wp = config.get('collapse_wp', False) fontsize = config.get('fontsize', 10.0) # pyplot params plt.rcParams['xtick.bottom'] = plt.rcParams['xtick.labelbottom'] = False plt.rcParams['xtick.top'] = plt.rcParams['xtick.labeltop'] = True plt.rcParams['font.size'] = fontsize # find number of displayed lines disp = 0 for wp in wps: if collapse_wp: disp += 1 else: disp += len(wp['tasks']) disp += 1 if show_delivmile else 0 disp -= 1 # axis range max_month = 0 # to be computed # plot fig, ax = plt.subplots() ticks = [] labels = [] wpspace = len(wps) for i, wp in enumerate(wps): wpspace_size = 0.5 * wpspace if collapse_wp: # WP only wp_start = min([task[1] for task in wp['tasks']]) wp_end = max([task[2] for task in wp['tasks']]) ticks.append(disp + wpspace_size) labels.append('WP' + str(i + 1 - wp_offset)) ax.broken_barh([(wp_start - 1, wp_end - wp_start + 1)], (disp - width / 2.0 + wpspace_size, width), facecolors=wp['color']) if wp_end > max_month: max_month = wp_end + 1 disp -= 1 else: # tasks for task in wp['tasks']: ticks.append(disp + wpspace_size) labels.append(task[0]) ax.broken_barh([(task[1] - 1, task[2] - task[1] + 1)], (disp - width / 2.0 + wpspace_size, width), facecolors=wp['color']) if task[2] > max_month: max_month = task[2] + 1 disp -= 1 # deliverables and milestones if show_delivmile: ticks.append(disp + wpspace_size) labels.append('WP' + str(i + 1 - wp_offset) + ' Deliverables and Milestones') ax.scatter(wp['deliverables'], [disp + width / 4.0 + wpspace_size] * len(wp['deliverables']), s=markersize, color=wp['color'], marker="^") if len(wp['milestones']) > 0: ax.scatter(wp['milestones'], [disp - width / 4.0 + wpspace_size] * len(wp['milestones']), s=markersize, color=wp['color'], marker="d") disp -= 1 wpspace -= 1 ax.set_yticks(ticks) ax.set_yticklabels(labels) ax.set_xticks(range(0, max_month + 1, 6)) ax.set_xticklabels(['M' + str(x) for x in range(0, max_month + 1, 6)]) ax.set_axisbelow(True) ax.grid(True, axis='x') make_axes_area_auto_adjustable(ax)
no_eggs = [line for line in uniq_copes.index if line not in uniq_eggs.index] copes_match = copes[~copes['sample_original_projname'].isin(no_eggs)] # get the average lat and lon of the samples for each project lat_lon = copes.groupby('sample_original_projname').agg({ 'object_lat': ['mean'], 'object_lon': ['mean'] }) lat_lon = eggs.groupby('sample_original_projname').agg({ 'object_lat': ['mean'], 'object_lon': ['mean'] }) fig1, ax1 = plt.subplots() uniq_copes.plot(kind='barh', ax=ax1) make_axes_area_auto_adjustable(ax1) ax1.set_title('All Copepods (mean lat, mean long)') ax1.set_ylabel('Project Name') ax1.set_xlabel('# Copepods') for ii, item in enumerate(uniq_copes.iteritems()): lat = lat_lon.loc[item[0]]['object_lat']['mean'] lon = lat_lon.loc[item[0]]['object_lon']['mean'] ax1.text(item[1] + 3, ii + 0.25, f'({np.round(lat,2)}, {np.round(lon,2)})', color='blue', fontweight='bold') fig1, ax1 = plt.subplots() uniq_eggs.plot(kind='barh', ax=ax1, color='m')
def axis_on(self): self.axes.set_axis_on() make_axes_area_auto_adjustable(self.axes)
=================================== """ import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable plt.figure() ax = plt.axes([0, 0, 1, 1]) ax.set_yticks([0.5]) ax.set_yticklabels(["very long label"]) make_axes_area_auto_adjustable(ax) ############################################################################### plt.figure() ax1 = plt.axes([0, 0, 1, 0.5]) ax2 = plt.axes([0, 0.5, 1, 0.5]) ax1.set_yticks([0.5]) ax1.set_yticklabels(["very long label"]) ax1.set_ylabel("Y label") ax2.set_title("Title") make_axes_area_auto_adjustable(ax1, pad=0.1, use_axes=[ax1, ax2]) make_axes_area_auto_adjustable(ax2, pad=0.1, use_axes=[ax1, ax2])
with open(options.legend) as f: labels = f.read().splitlines() plt.figure() ax = plt.axes() weights = zip(*weightList) if options.non_zero: weights,feature_names = zip(*[d for d in zip(weights,feature_names) if np.any(np.array(d[0])>options.limit) ]) if options.sort: sortingmeasure = [np.sum(np.array(d)) for d in weights] weights,feature_names = zip(*[(x,f) for (s,x,f) in sorted(zip(sortingmeasure,weights,feature_names), key=lambda pair: pair[0],reverse=True)]) width = 1./(len(weightList)+1) offset = -0.5 * width * (NumberOfWeightFiles-1) x_pos = 1.0 * np.arange(len(feature_names)) l = '' for i in xrange(NumberOfWeightFiles): if len(options.legend) > 0: l = labels[i] plt.bar(x_pos+offset, [w[i] for w in weights], color=colors[i],align='center', width=width,log=options.logscale,linewidth=0,label=l) offset += width plt.xticks(x_pos, feature_names, rotation='vertical', fontsize=options.fontsize) plt.legend(prop={'size':6}) make_axes_area_auto_adjustable(ax) plt.savefig(options.out_file)