def stack_plot(fr, outfile, normalize=False, dont_stack=False, max_n=20): if len(fr.columns) > max_n: # reformat columns and group together nonsignificant ones js = sorted([ (c,fr[c].sum()) for c in fr.columns ], key=lambda j: j[1], reverse=True) top_js = [ i[0] for i in js[:max_n]] rest_js = [ i[0] for i in js[max_n:]] # replace fr['Others']=fr[rest_js].sum(axis=1) # remove fr=fr.drop(rest_js, axis=1) labels = top_js+['Others'] else: js = sorted([ (c,fr[c].sum()) for c in fr.columns ], key=lambda j: j[1], reverse=True) labels = [ i[0] for i in js] pyplot.figure(figsize=(13, 8)) colors = generate_n_colors(len(labels)) if dont_stack: for color, label in zip(colors, labels): pyplot.plot(fr.index, fr[label], color=color, label=label, linewidth=2) else: pyplot.stackplot(fr.index, fr[labels].T, labels=labels)#, colors=colors #fr.plot(kind='area') pyplot.legend(loc=2) pyplot.ylabel('Lines of code') pyplot.tight_layout() pyplot.savefig(outfile)
def stacked_trajectory_plot(xlabel="generation"): colors_lighter = [ "#A567AF", "#8F69C1", "#8474D1", "#7F85DB", "#7F97DF", "#82A8DD", "#88B5D5", "#8FC0C9", "#97C8BC", "#A1CDAD", "#ACD1A0", "#B9D395", "#C6D38C", "#D3D285", "#DECE81", "#E8C77D", "#EDBB7A", "#EEAB77", "#ED9773", "#EA816F", "#E76B6B", ] mpl.rcParams["font.size"] = 18 haplotypes = get_all_haplotypes() trajectories = [get_trajectory(haplotype) for haplotype in haplotypes] plt.stackplot(range(generations), trajectories, colors=colors_lighter) plt.ylim(0, 1) plt.ylabel("frequency") plt.xlabel(xlabel)
def plot_stack_candidates(tweets, cands, interval, start = 0, \ end = MAX_TIME // 60, tic_inc = 120, save_to = None): ''' Plots stackplot for the candidates in list cands over the time interval ''' period = range(start, end, interval) percent_dict = tweets.mention_minute_percent(cands, interval, period) y = [] fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT)) legends = [] for candidate in percent_dict: y.append(percent_dict[candidate]) legends.append(CANDIDATE_NAMES[candidate]) plt.stackplot(period, y) plt.title("Percentage of Mentions per {} minutes before, during, \ and after debate".format(interval)) plt.xlabel("Time") plt.ylabel("Number of Tweets") plt.legend(y, legends) ticks_range = range(start, end, tic_inc) labels = list(map(lambda x: str(x - start) + " min", ticks_range)) plt.xticks(ticks_range, labels, rotation = 'vertical') plt.xlim( (start, end) ) plt.ylim( (0.0, 1.0)) if save_to: fig.savefig(save_to) plt.show()
def plot2(): ### number of settlements,cropping: abandoned/sown, soil degradation, forest state fig = plt.figure(figsize=(12, 7)) ### number of settlements plt.subplot(221) plt.plot(number_settlements_evo) plt.title("number of settlements") ### cropping: abandoned/sown plt.subplot(222) plt.plot(abnd_sown_evo[:, 0], "r") plt.plot(abnd_sown_evo[:, 1], "g") plt.title("abandoned/sown") ### soil degradation plt.subplot(223) plt.plot(soil_deg_evo[0]) plt.title("soil degradation") ### forest state plt.subplot(224) plt.stackplot(np.arange(N),forest_evo[0],forest_evo[1],forest_evo[2],colors=['#FF9900', '#66FF33','#336600']) plt.title("forest state") plt.tight_layout() fig.savefig(picture_directory+'2_panel.png',dpi=200) plt.close(fig)
def stackplot(data, x, y, hue, cmap=palettes.neon): xs = np.array(data[x]) yss = [] labels = [] for k,grp in data.groupby(hue): labels.append(k) grp_xs = grp[x].tolist() grp_ys = grp[y].tolist() ys = [] for v in xs: if len(grp_xs) > 0 and grp_xs[0] == v: ys.append(grp_ys.pop(0)) grp_xs.pop(0) else: if len(ys) == 0: ys.append(0.) else: ys.append(ys[-1]) assert len(grp_xs) == 0 assert len(grp_ys) == 0 assert len(ys) == len(xs) yss.append(np.array(ys, dtype=float)) if cmap is not None: colors = colors_from_hue(data, hue, cmap) else: colors = None plt.stackplot(xs, *yss, labels=labels, colors=colors) plt.ylabel(y) plt.xlabel(x) plt.gca().autoscale(tight=True) plt.gca().margins(y=0.1)
def plot3(): ### number of settlements, cropping: abandoned/sown, soil degradation, total real income fig = plt.figure(figsize=(12,7)) crop_yield_evo[np.isnan(crop_yield_evo)]=0 ### number of settlements plt.subplot(221) plt.plot(crop_yield_evo) plt.title("crop yield") ### ecoserv benefit plt.subplot(222) plt.plot(eco_benefit_evo) plt.title("eco benefit") ### soil degradation plt.subplot(223) plt.plot(trade_income_evo) plt.title("trade strength") ### total real income plt.subplot(224) plt.stackplot(np.arange(N),np.nanmean(crop_yield_evo,1)*1.1,np.nanmean(eco_benefit_evo,1)*10,np.nanmean(trade_income_evo,1)*6000) plt.title("total real income") plt.tight_layout() fig.savefig(picture_directory+'3_panel.png',dpi=200) plt.close(fig)
def plot(self): # Read events. #self.read_simple_events() #self.read_external_events() self.read_events() self.scale(self.scale_factor) # Set the plot size. grid_row = 2 grid_fig_col = self.num_simple_events / 2 grid_legend_col = 8 grid_col = grid_fig_col + grid_legend_col fig = plt.figure(figsize = (grid_col, grid_row * 6)) # Plot simple events. plt.subplot2grid((grid_row, grid_col), (0, 0), colspan = grid_fig_col) x = np.arange(self.num_simple_events) # Prepare colors. colors = self.get_colors(len(V8_STATES_PLOT)) plt.stackplot(x, [self.data[key] for key in V8_STATES_PLOT], colors = colors) # Set the axis limits. plt.xlim(xmin = 0, xmax = self.num_simple_events - 1) plt.ylim(ymin = 0, ymax = self.sampling_period) # Draw legend. plt.subplot2grid((grid_row, grid_col), (0, grid_col - 1)) total_ticks = self.num_simple_events * self.sampling_period plt.table(cellText = [[str(100 * sum(self.data[key]) / total_ticks) + ' %'] for key in reversed(V8_STATES_PLOT)], rowLabels = V8_STATES_PLOT[::-1], rowColours = colors[::-1], colLabels = ['Ticks'], loc = 'center') plt.xticks([]) plt.yticks([]) # Plot external events. plt.subplot2grid((grid_row, grid_col), (1, 0), colspan = grid_fig_col) x = np.arange(self.num_external_events) # Prepare colors. colors = self.get_colors(len(EXTERNAL_DETAILS)) plt.stackplot(x, [self.data_external[key] for key in EXTERNAL_DETAILS], colors = colors) # Set the axis limits. plt.xlim(xmin = 0, xmax = self.num_external_events - 1) plt.ylim(ymin = 0, ymax = self.sampling_period) # Draw legend. plt.subplot2grid((grid_row, grid_col), (1, grid_col - 3), colspan = 3) total_ticks = 0 for key in EXTERNAL_DETAILS: total_ticks += sum(self.data_external[key]) + 1 plt.table(cellText = [[str(100 * sum(self.data_external[key]) / total_ticks) + ' %', str(sum(self.num_external[key]))] for key in reversed(EXTERNAL_DETAILS)], rowLabels = EXTERNAL_DETAILS[::-1], rowColours = colors[::-1], colLabels = ['Ticks', '# of Times'], loc = 'center') plt.xticks([]) plt.yticks([]) # Finally draw the plot. plt.tight_layout() plt.show()
def stacked_trajectory_plot(xlabel="generation"): mpl.rcParams['font.size']=18 haplotypes = get_all_haplotypes() trajectories = [get_trajectory(haplotype) for haplotype in haplotypes] plt.stackplot(range(generations), trajectories, colors=colors_lighter) plt.ylim(0, 1) plt.ylabel("frequency") plt.xlabel(xlabel)
def stackPlot(self, mergeMeth, xAxis, lst1, lst, lst3): xLims = plt.xlim(-.05, (xAxis +.05)) yLims = plt.ylim(0, max(mergeMeth) + 1) #fig, ax = plt.subplots() plt.stackplot(xAxis, lst1, lst2, lst3, colors=['m','c','y']) plt.show()
def makePlot(fn=getCosDistribution): # collect data h = 60 linePlots = [] stackedPlots = { 'labels': [], 'data': [], 'colors': [], } for line in lines: distribution = fn(line['schedule'], line['capacity']) distribution = rotate(distribution, -line.get('offset', 0)) distribution = distribution[3*h:] + distribution[:3*h] distribution = distribution[1*h:23*h] if line.get('stacked'): stackedPlots['data' ].append(distribution) stackedPlots['colors'].append(line['color']) stackedPlots['labels'].append(line['line']) else: linePlots.append({ 'y': distribution, 'color': line['color'], 'linestyle': line.get('linestyle', '-'), 'linewidth': line.get('linewidth', 2), 'alpha': line.get('alpha', 1), }) X = [t/60.0 for t in range(4*h, 26*h)] # make plot matplotlib.rcParams.update({'font.size': 16}) fig, ax = plot.subplots(facecolor="white", figsize=(13,7), dpi=100) ax.xaxis.set_major_formatter(ticker.FuncFormatter(lambda d, _: str(d%24)+"h")) ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda d, _: "{:,}".format(int(d)))) plot.xlim(4, 26) plot.ylim(0, 35000) plot.xticks(range(4,27, 2)) plot.ticklabel_format(axis='x',) plot.minorticks_on() plot.grid(color='#000000', alpha=0.2, linestyle='-', linewidth=0.8, which='both') ax.yaxis.grid(color='#000000', alpha=0.1, linestyle='-', linewidth=0.4, which='minor') # plot.grid(color='#000000', b=True, which='minor', axis='x', alpha=0.15, linestyle='-', linewidth=0.5, xdata=range(5,27, 2)) ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(2)) if len(stackedPlots['data']) > 0: plot.stackplot(X, *(stackedPlots['data']), colors=stackedPlots['colors'], alpha = 0.5, linewidth = 0) for p in linePlots: plot.plot(X, p['y'], alpha=p['alpha'], color=p['color'], linewidth=p['linewidth'], linestyle=p['linestyle'],) # plot.axes(axisbg='w') plot.show()
def stacked(asim, msim): if len(asim) != len(msim): raise Exception("The Replacement and Maintenance sets arent the same lenght") else: plt.stackplot(range(0, len(asim)), [asim, msim], colors=["#377EB8", "#55BA87"]) plt.legend([mpatches.Patch(color="#377EB8"), mpatches.Patch(color="#55BA87")], ["Replacement", "Maintenance"]) plt.title("Expected Financial Consequence - Replacement & Maintenance") plt.xlabel("Years") plt.ylabel("Fin. Consequence (k)")
def plot_population_drift(drift_data, title): generations = range(drift_data.shape[1]) xs = range(drift_data.shape[0]) colors = [str(hex(SKIN_COLORS[x])).replace("0x", "#") for x in xs] plt.stackplot(generations, drift_data, baseline="zero", colors=colors) plt.xlabel("Generations") plt.ylabel("Frequency") plt.title("Phenotype Drift:%s" % (title)) plt.show()
def stacked_trajectory_plot(history, generations, name = 'stacked_trajectory', xlabel="generation"): colors_lighter = ["#A567AF", "#8F69C1", "#8474D1", "#7F85DB", "#7F97DF", "#82A8DD", "#88B5D5", "#8FC0C9", "#97C8BC", "#A1CDAD", "#ACD1A0", "#B9D395", "#C6D38C", "#D3D285", "#DECE81", "#E8C77D", "#EDBB7A", "#EEAB77", "#ED9773", "#EA816F", "#E76B6B"] mpl.rcParams['font.size']=18 haplotypes = get_all_haplotypes(history, generations) trajectories = [get_trajectory(haplotype, generations, history) for haplotype in haplotypes] plt.stackplot(range(generations), trajectories, colors=colors_lighter) plt.ylim(0, 1) plt.ylabel("frequency") plt.xlabel(xlabel) plt.savefig(name + '.png', bbox_inches='tight', dpi = 600)
def plotLats(classifNr,dx): x = [classifNr[i] for i in classifNr] n = 180/dx + 1 y = np.arange(-90,90+dx,dx) fig = plt.figure() plt.stackplot(y,x,alpha = 0.4,colors = colors) plt.margins(0,0) plt.title('Classifications and latitudes, percentage') plt.xlabel('Latitudes') plt.xticks(y) plt.show()
def test05(): k = [1,2,3,4,5] a = [2,3,2,3,2] b = [4,1,5,3,5] c = [1,4,2,2,3] d = [3,2,1,2,0] plt.stackplot(k, a, b, c, d, colors=['r', 'g', 'b', 'y']) plt.plot([],[],label='a',color='r',linewidth=5) plt.plot([],[],label='b',color='g',linewidth=5) plt.plot([],[],label='c',color='b',linewidth=5) plt.plot([],[],label='d',color='y',linewidth=5)
def stack_plots(): days = [1,2,3,4,5] sleeping = [7,8,6,11,7] eating = [2,3,4,3,2] working = [7,8,7,2,2] playing = [8,5,7,8,13] pyplot.plot([], [], color='magenta', label='Sleeping', linewidth=3) pyplot.plot([], [], color='cyan', label='Eating', linewidth=3) pyplot.plot([], [], color='red', label='Working', linewidth=3) pyplot.plot([], [], color='black', label='Playing', linewidth=3) pyplot.stackplot(days, sleeping, eating, working, playing, colors=['magenta', 'cyan', 'red', 'black']) pyplot_apply_2d()
def test_stackplot_baseline(): np.random.seed(0) def layers(n, m): def bump(a): x = 1 / (.1 + np.random.random()) y = 2 * np.random.random() - .5 z = 10 / (.1 + np.random.random()) for i in range(m): w = (i / float(m) - y) * z a[i] += x * np.exp(-w * w) a = np.zeros((m, n)) for i in range(n): for j in range(5): bump(a[:, i]) return a d=layers(3, 100) fig = plt.figure() plt.subplot(2, 2, 1) plt.stackplot(range(100), d.T, baseline='zero') plt.subplot(2, 2, 2) plt.stackplot(range(100), d.T, baseline='sym') plt.subplot(2, 2, 3) plt.stackplot(range(100), d.T, baseline='wiggle') plt.subplot(2, 2, 4) plt.stackplot(range(100), d.T, baseline='weighted_wiggle')
def make_scaling_plot(params, title, path, axis=None): m = run_model(**params) purple = '#BBA4D1' blue = '#3399CC' plt_title(title) plt.stackplot([(tick * params['sec_per_tick']) / 60.0 for tick in range(m.ticks)], m.builders_in_use, m.builders_available, colors=(purple, blue), linewidth=0) plt.legend([mpatches.Patch(color=purple), mpatches.Patch(color=blue)], ['Busy Builder Machines','Available Builder Machines']) plt.xlabel('Time (m)') plt.ylabel('Machines') if axis: plt.axis(axis) plt_save(path)
def plot(dates, f_frac, m_frac, title, f_overall, m_overall): x_spacing = [i+1 for i in range(len(dates))] plt.stackplot(x_spacing, f_frac, m_frac, labels=('Female', 'Male'), colors=('r','b')) plt.axhline(f_overall, linewidth=2, color='m') plt.axhline(m_overall, linewidth=2, color='c') plt.xlabel('Date') plt.ylabel('Fraction of New Yorker bylines') plt.title(title) plt.xticks(takespread(x_spacing, MAX_X_TICKS), takespread(dates, MAX_X_TICKS), rotation=45) plt.yticks([i/10.0 for i in range(10)]) plt.legend(('Overall female', 'Overall male', 'Female', 'Male'), loc='center right', fontsize='x-small') plt.autoscale() plt.show()
def plot3(): ### number of settlements, cropping: abandoned/sown, soil degradation, total real income fig = plt.figure(figsize=(12,7)) crop_yield_evo[np.isnan(crop_yield_evo)]=0 ### number of settlements plt.subplot(221) plt.plot(crop_yield_evo) plt.title("crop yield") ### ecoserv benefit plt.subplot(222) plt.plot(eco_benefit_evo) plt.title("eco benefit") ### soil degradation plt.subplot(223) plt.plot(trade_income_evo) plt.title("trade strength") ### total real income plt.subplot(224) stacks = plt.stackplot(np.arange(N),np.nanmean(crop_yield_evo,1),np.nanmean(eco_benefit_evo,1),np.nanmean(trade_income_evo,1)) LegendProxies = [] for stack in stacks: LegendProxies.append(plt.Rectangle((0,0),1,1,fc=stack.get_facecolor()[0])) print ('stack') plt.legend(LegendProxies,['crops', 'ess', 'trade'], loc=0) plt.title("total real income") plt.tight_layout() fig.savefig(picture_directory+'3_panel.png',dpi=200) plt.close(fig)
def generate(self, trend_file): ''' Generates the trend chart and saves it as a PNG image using matplotlib Parameters - trend_file : file name to save chart image to ''' fig, axes = plt.subplots() # add data x_values = range(len(self.builds)) plots = plt.stackplot(x_values, self.stages.values()) plt.xticks(x_values, self.builds, rotation=45, size=10) # label axes and add graph title axes.set_xlabel("Builds", {'fontsize': 14}) axes.xaxis.set_label_coords(1.05, -0.05) axes.set_ylabel("Duration [s]", {'fontsize': 14}) axes.set_title("Build stages trend", {'fontsize': 22}) # display legend legend_proxies = [] for plot in plots: legend_proxies.append( plt.Rectangle((0, 0), 1, 1, fc=plot.get_facecolor()[0])) # add legend in reverse order, in upper left corner axes.legend(legend_proxies[::-1], self.stages.keys()[::-1], loc=2) # save figure plt.savefig(trend_file)
def plot_computable(): # get data sizes = [] durations_compute = [] durations_overhead = [] for p in client.eval.computables.find({"query.$comment.exp":"computable"}).sort("query.$comment.db-size",1): compute = p["computables"][1]["compute"] sizes.append(p["query"]["$comment"]["db-size"]) durations_compute.append(compute * 1000.0) durations_overhead.append((p["total"]-compute) * 1000.0) durations_stack = np.row_stack((durations_overhead, durations_compute)) with PdfPages('computable-durations.pdf') as pdf: # format plot #fig, ax = plt.subplots() plt.figure(figsize=(8,5)) plt.xlabel('db size (#docs)') plt.ylabel('duration (ms)') plt.axis([0, 100000, 0.0, 80]) # fill plot polys = plt.stackplot(sizes, durations_stack) #construct legend: legendProxies = [] for poly in polys: legendProxies.append(plt.Rectangle((0, 0), 1, 1, fc=poly.get_facecolor()[0])) plt.legend(legendProxies, ["overhead", "compute time"], loc=2) # save plot # plt.show() pdf.savefig() plt.close()
def format_matlab(index, plot_list, day = True, colors_list = None): if not colors_list: colors_list = [] color_norm = colors.Normalize(vmin=0, vmax=len(plot_list)-1) scalar_map_day = cmx.ScalarMappable(norm=color_norm, cmap='Greens') scalar_map_night = cmx.ScalarMappable(norm=color_norm, cmap='Reds') for i in range(len(plot_list)): plot_list[i] = [x[0] for x in plot_list[i].values] if day: colors_list.append(scalar_map_day.to_rgba(i)) else: colors_list.append(scalar_map_night.to_rgba(i)) print "Plot" plt.stackplot(index, plot_list, colors=colors_list) plt.show() return colors_list
def main_panel(): """ plot of the main four parameter sets: 1) income sources (not stacked) 2) population and settlements (on two axes in one plot) 3) forest state (as is in same colors) 4) soil degradation :return: None """ fig = plt.figure(figsize=(12, 7)) # population and settlements: ax1 = fig.add_subplot(221) ln1 = ax1.plot(np.sum(population_evo, 1), 'b', label='population') tax1 = ax1.twinx() ln2 = tax1.plot(number_settlements_evo, 'r', label='#settlements') lns = ln1 + ln2 labs = [l.get_label() for l in lns] ax1.legend(lns, labs, loc=0) ax1.grid(axis='x') tax1.grid(axis='x') plt.title('population') # income sources (not stacked) ax2 = fig.add_subplot(222) ln21 = ax2.plot(np.arange(N), np.nanmean(crop_yield_evo, 1), 'g', label='ag') ln22 = ax2.plot(np.arange(N), np.nanmean(eco_benefit_evo, 1), 'r', label='es') ln23 = ax2.plot(np.arange(N), np.nanmean(trade_income_evo, 1), 'b', label='trade') tax2 = ax2.twinx() ln24 = tax2.plot(np.nansum(real_income_pc_evo, 1), 'k', label='pc') lns = ln21 + ln22 + ln23 + ln24 labs = [l.get_label() for l in lns] ax2.legend(lns, labs, loc=0) ax2.grid(axis='x') tax2.grid(axis='x') plt.title('income') # forest state plt.subplot(223) stacks = plt.stackplot(np.arange(N),forest_evo[0], forest_evo[1], forest_evo[2], colors=['#FF9900', '#66FF33', '#336600']) plt.xlim(0, N) plt.ylim(0, 100000) legend_proxies = [] for stack in stacks: legend_proxies.append(plt.Rectangle((0, 0), 1, 1, fc=stack.get_facecolor()[0])) plt.legend(legend_proxies, ['cut', 'regrowth', 'climax'], loc=0) plt.title('forest state') # soil degradation plt.subplot(224) plt.plot(soil_deg_evo[0]) plt.grid(axis='x') plt.title("soil degradation") plt.tight_layout() fig.savefig(picture_directory+'0_main_panel.png', dpi=300)
def project_f(initial_state, det_curves, yrs, r): sim = np.zeros(yrs) # replaced = np.zeros(yrs) state = initial_state.copy() for i in range(0, yrs): sim[i] = state["Exp(Fin)"].sum() state = update_state(state, det_curves, replace=r) # replaced[i] = len(state[state['Age']==0]) fig = plt.figure() plt.stackplot(range(0, yrs), sim) if r == 1: plt.title("Financial Consequence for Asset Group with Replacement") else: plt.title("Financial Consequence for Asset Group wo Replacement") plt.xlabel("Years") plt.ylabel("Fin. Consequence (k)") return sim
def make_image(self, data, path_hash): total_events, open_events, done_events, timestamps = self.split_total_open_done(data) plt.stackplot(timestamps, [done_events, open_events, total_events], labels=self.labels, colors=self.colors, alpha=0.4) plt.gca().get_yaxis().set_major_formatter(self.CustomMajorFormatter()) plt.gca().get_xaxis().set_major_formatter(self.CustomTimestampFormatter()) plt.xticks(rotation=15) plt.legend(loc='upper left') plt.gcf().set_size_inches(10, 6) filename = self.make_file_path(path_hash) plt.savefig(filename, dpi=100, bbox_inches='tight', pad_inches=0.1) plt.close() return filename.replace('/static', '')
def stackPlot(self, mergeList, xAxis, lst1, lst2, lst3): # L & R side boundaries x = [mergeList.index(i) for i in mergeList] xLims = plt.xlim(-.05, (xAxis +.05)) yLims = plt.ylim(0, max(mergeList) + 1) #fig, ax = plt.subplots() plt.stackplot(x, lst1, lst2, lst3, colors=['m','c','y']) print("x Axis: %d" %xAxis) print(mergeList) print("list 1: %s" %lst1) print("list 2: %s" %lst2) print("list 3: %s" %lst3) plt.show()
def plot_stack(ifs): """ plot stack type = 'intuitionistic' type only """ fig = plt.figure() indices, mus, nus, pis = ifs.elements_split() plt.stackplot(indices, mus, pis, nus, colors=['b','c','g']) plt.plot([],[],color='b', label='Membership', linewidth=5) plt.plot([],[],color='c', label='Indeterminacy', linewidth=5) plt.plot([],[],color='g', label='Non-membership', linewidth=5) plt.xlabel('Universe') plt.ylabel('Degrees') plt.legend(loc='upper right')
def generate_graph(values, title=None, fill=False): plt.close() fig, ax = plt.subplots() if title: ax.set_title(title) # Add the single letter colors. colors_list = list(six.iteritems(colors.cnames)) with plt.style.context('fivethirtyeight'): for (label, xs, ys), color in zip(values, colors_list): if fill: plt.stackplot(xs, ys, colors=color, alpha=0.4) plt.plot(xs, ys, color=color[0], alpha=0.9, linewidth=1.5, label=label) else: plt.plot(xs, ys, alpha=0.8,marker='o', color=color[0], label=label) fig.autofmt_xdate() plt.legend(loc=2) plt.grid(True)
def simpleBarChart(tweet, f_retweets, nf_retweets, interval, filename, saving): print Fore.BLUE + "Now making a nice picture" + Fore.RESET f_times = [] for retweet in f_retweets: f_times.append(retweet['created_at']) nf_times = [] for retweet in nf_retweets: nf_times.append(retweet['created_at']) times = f_times + nf_times # setup bins for bar graph. # range: time of first tweet -> time of last tweet first = min(times) last = max(times) f_intervals = {} nf_intervals = {} for time in f_times: elapsed_intervals = math.floor((time - first).total_seconds() / interval) f_intervals[elapsed_intervals] = f_intervals.get(elapsed_intervals, 0) + 1 nf_intervals[elapsed_intervals] = nf_intervals.get(elapsed_intervals, 0) for time in nf_times: elapsed_intervals = math.floor((time - first).total_seconds() / interval) nf_intervals[elapsed_intervals] = nf_intervals.get(elapsed_intervals, 0) + 1 f_intervals[elapsed_intervals] = f_intervals.get(elapsed_intervals, 0) #plt.yscale('symlog') plt.title(tweet['text'].replace('$', "<Dollar>") + '\n' + tweet['user']['screen_name']) plt.ylabel('Retweets') plt.xlabel('%d second intervals after initial tweet (at %s)' \ % (interval, str(tweet['created_at'])) ) plt.stackplot(f_intervals.keys(), f_intervals.values(), nf_intervals.values(), colors=('r', 'y')) if saving: plt.savefig(filename) plt.close() else: plt.show()
for i in range(20): for j in range(2000): if i < 7: bucket[0][j] += histogram[i][j] elif i < 13: bucket[1][j] += histogram[i][j] else: bucket[2][j] += histogram[i][j] data = pd.DataFrame( { 'breed': bucket[0], 'general': bucket[1], 'forage': bucket[2] }, index=range(1, 2001)) # We need to transform the data from raw data to percentage (fraction) data_perc = data.divide(data.sum(axis=1), axis=0) # Make the plot plt.stackplot(range(1, 2001), data_perc["breed"], data_perc["general"], data_perc["forage"], labels=['Breeders', 'Generalists', 'Foragers']) plt.legend(loc='upper left') plt.margins(0, 0) plt.title(inVal) plt.show()
# H_1[i-1]=h1+h2+h3 # # i1=np.sum(I.loc[I['Time']==i]['mwh_1'].values) # i2=np.sum(I.loc[I['Time']==i]['mwh_2'].values) # i3=np.sum(I.loc[I['Time']==i]['mwh_3'].values) # # I_1[i-1]=i1+i2+i3 w1 = np.sum(Q_2.loc[Q_2['Time'] == i]['Wind'].values) W_1[i - 1] = w1 s1 = np.sum(Q_2.loc[Q_2['Time'] == i]['Solar'].values) S_1[i - 1] = s1 # L=CA_load[year*365*24:year*365*24+364*24] T = np.sum(np.reshape(T_1, (364, 24)), axis=1) S = np.sum(np.reshape(S_1, (364, 24)), axis=1) W = np.sum(np.reshape(W_1, (364, 24)), axis=1) must_run = must_run_daily hydro = daily_hydro[year * 365:year * 365 + 364] load = daily_load[year * 365:year * 365 + 364] imports = daily_path[year * 365:year * 365 + 364] return T, W, S, must_run, hydro, load, imports T, W, S, M, H, L, I = grab_data(300) plt.stackplot(range(0, 364), T, W, S, M, H, I * 24, alpha=0.7) plt.plot(L * 24)
# del time_agg["predict"] # del time_agg["update"] # del time_agg["parse"] # del time_agg["add and remove"] # del time_agg["store"] # del time_agg["plot"] # del time_agg["pre_localize and align"] # del time_agg["post_localize"] # del time_agg["load"] print(len(time_agg), len(det_steps)) plots = [time_agg[key] for key in time_agg.keys()] legend = [key for key in time_agg.keys()] #legend = [legend[1],legend[2],legend[3],legend[0]] #plots = [plots[1],plots[2],plots[3],plots[0]] plt.stackplot(det_steps, plots) plt.legend(legend, fontsize=18) plt.xlabel("Frames between detection", fontsize=20) plt.ylabel("Relative Time Utilization", fontsize=20) plt.xlim([0, 45]) plt.ylim([0, 1]) # combine predict and update # combine detect and parse # combine add and remove and store # combine pre, localize, and post # remove plot # divide by total #%% Compute MOTA at a variety of IOU requirements track_dir = data_paths["test_im"]
np.random.seed(1536252) years = np.linspace(2000, 2010, N, dtype=np.int64) expense1 = np.random.randint(lim1, lim2, N) expense2 = np.random.randint(lim1, lim2, N) expense3 = np.random.randint(lim1, lim2, N) expense4 = np.random.randint(lim1, lim2, N) expense5 = np.random.randint(lim1, lim2, N) expenses = [expense1, expense2, expense3, expense4, expense5] Labels = ['Education', 'Medication', 'Charity', 'Infrastructure', 'Defence'] Colours = ['blue', 'green', 'red', 'black', 'yellow'] # simple # plt.stackplot(years, expense1, colors=['green'], labels=['Education']) # Batch # plt.stackplot(years, expense1, expense2, expense3, expense4, expense5, # colors=['blue', 'green', 'red', 'black', 'yellow'], # labels=['Education', 'Medication', 'Charity', 'Infrastructure', 'Defence']) # Alternatively, this way is simpler and compact plt.stackplot(years, expenses, colors=Colours, labels=Labels) plt.xlabel('Years') plt.ylabel('Accumulated Expenses') plt.title('Stacked Plot: Expenses in {} city for 11 years in {} {}'.format( 'Coimbatore', 'Million', 'Rupees')) plt.grid(True) plt.legend() plt.show()
plt.hist(population_ages,bins,histtype="bar",rwidth=0.8) plt.xlabel("osa x") plt.ylabel("osa y") plt.title("zajímavej graf\nČekni to") plt.legend() plt.show()""" # scatter """coords.append([[random.randrange(15) for _ in range(20)], [random.randrange(15) for _ in range(20)]]) coords.append([[random.randrange(15) for _ in range(20)], [random.randrange(15) for _ in range(20)]]) plt.scatter(coords[0][0], coords[0][1], label="skitscat", color="k",marker="*",s=100) plt.scatter(coords[1][0], coords[1][1], label="skitscat2", color="r",marker="o",s=100)""" # stack """days = [1, 2, 3, 4, 5, 6] sleeping = [random.randrange(8) for _ in range(len(days))] eating = [random.randrange(8) for _ in range(len(days))] working = [random.randrange(8) for _ in range(len(days))] playing = [random.randrange(8) for _ in range(len(days))] plt.stackplot(days, sleeping, eating, working, playing, colors=["k", "r", "c", "b"],labels=["sl","eat","work","play"]) plt.xlabel("osa x") plt.ylabel("osa y") plt.title("zajímavej graf\nČekni to") plt.legend() plt.show()""" # pie
def plot_terminal_voltage(soln, mesh, R_cc, param): # Create voltage object voltage = Voltage(soln, mesh, R_cc, param) # Convert to dimensional time t = soln.t * param.tau_d_star # Font stuff plt.rc("text", usetex=True) plt.rc("font", family="serif") # Make plots fig = plt.figure() plt.subplot(2, 1, 1) plt.plot(t, voltage.v_term, label="V") plt.xlim([t[0], t[-1]]) plt.ylim([param.V_min, param.V_max]) plt.xlabel(r"$t$ [s]", fontsize=11) plt.ylabel("Voltage [V]", fontsize=11) plt.title("Voltage", fontsize=11) plt.legend() plt.subplot(2, 1, 2) plt.stackplot( t, voltage.U_eq - voltage.U_eq_init, voltage.eta_r, voltage.eta_c, voltage.Delta_Phi_elec, voltage.Delta_Phi_solid, voltage.Delta_Phi_cc, labels=[ r"$\mathcal{{U}}_{{\mathrm{{eq}}}}$" r"$- \mathcal{{U}}_{{\mathrm{{eq,init}}}}$ [V]", r"$\eta_{{\mathrm{{r}}}}$", r"$\eta_{{\mathrm{{c}}}}$", r"$\Delta \Phi_{{\mathrm{{elec}}}}$", r"$\Delta \Phi_{{\mathrm{{solid}}}}$", r"$\Delta \Phi_{{\mathrm{{cc}}}}$", ], ) plt.xlim([t[0], t[-1]]) plt.xlabel(r"$t$ [s]", fontsize=11) plt.ylabel("Voltage [V]", fontsize=11) plt.title("Voltage", fontsize=11) plt.legend() fig.tight_layout() fig2 = plt.figure() plt.subplot(2, 3, 1) plt.plot(t, voltage.U_eq - voltage.U_eq_init) plt.xlabel(r"$t$ [s]", fontsize=11) plt.ylabel(r"$\mathcal{{U}}_{{\mathrm{{eq}}}}$" r"$- \mathcal{{U}}_{{\mathrm{{eq,init}}}}$ [V]") plt.subplot(2, 3, 2) plt.plot(t, voltage.eta_r) plt.xlabel(r"$t$ [s]", fontsize=11) plt.ylabel(r"$\eta_{{\mathrm{{r}}}}$ [V]") plt.subplot(2, 3, 3) plt.plot(t, voltage.eta_c) plt.xlabel(r"$t$ [s]", fontsize=11) plt.ylabel(r"$\eta_{{\mathrm{{c}}}}$ [V]") plt.subplot(2, 3, 4) plt.plot(t, voltage.Delta_Phi_elec) plt.xlabel(r"$t$ [s]", fontsize=11) plt.ylabel(r"$\Delta \Phi_{{\mathrm{{elec}}}}$ [V]") plt.subplot(2, 3, 5) plt.plot(t, voltage.Delta_Phi_solid) plt.xlabel(r"$t$ [s]", fontsize=11) plt.ylabel(r"$\Delta \Phi_{{\mathrm{{solid}}}}$ [V]") plt.subplot(2, 3, 6) plt.plot(t, voltage.Delta_Phi_cc) plt.xlabel(r"$t$ [s]", fontsize=11) plt.ylabel(r"$\Delta \Phi_{{\mathrm{{cc}}}}$ [V]") fig2.tight_layout()
fc="w") i = int(len(dates) * 0.75) c = int(contrib[-1] * 0.75) ax2.annotate('Unique Contributors', xy=(dates[i], contrib[i]), xytext=(datetime.date(2014, 1, 1), c), ha='right', size=options.font, arrowprops=arrow) # labels y_label = 'Commits' # Plot the data if options.stack: # stack plot handles = plt.stackplot(dates, data['commits']) for i in range(len(handles)): handles[i].set_label(contributors[i]) elif options.additions: #additions/deletions plot y_label = 'Additions / Deletions' n = len(contributors) for i in reversed(range(n)): x = numpy.array(dates) y = numpy.log10(numpy.array(data['in'][i, :])) if n == 1: label = 'Additions' else: label = contributors[i] + '(Additions)'
import matplotlib.pyplot as plt days = [1, 2, 3, 4, 5] sleeping = [7, 8, 6, 11, 7] eating = [2, 3, 4, 3, 2] working = [7, 8, 7, 2, 2] playing = [2, 3, 6, 8, 13] # Creating the labels plt.plot([], [], color="m", label="Sleeping", linewidth=5) plt.plot([], [], color="c", label="Eating", linewidth=5) plt.plot([], [], color="r", label="Working", linewidth=5) plt.plot([], [], color="k", label="Playing", linewidth=5) # Create the stack plot plt.stackplot(days, sleeping, eating, working, playing, colors=["m", "c", "r", "k"]) plt.xlabel("X") plt.ylabel("Y") plt.title("Graph 01\ncheck it out") # plt.legend() plt.show()
plt.subplot(221) colors = [ '#000000', '#666633', '#003333', '#663333', '#000066', '#006600', '#CCCC99', '#336666', '#660099', '#CD6600' ] labels = [ 'CLTXP', 'PATCB', 'NNTCB', 'NUETB', 'WYTCB', 'SOTCB', 'GETCB', 'HYTCB', 'BMTCB', 'ELNIB' ] plt.stackplot(ca_feature['year'], ca_feature['煤炭消耗量'], ca_feature['石油消耗量'], ca_feature['天然气消耗量'], ca_feature['核能消耗量'], ca_feature['风能消耗量'], ca_feature['太阳能消耗量'], ca_feature['地热能消耗量'], ca_feature['水能消耗量'], ca_feature['生物质能'], ca_feature['净进口电量'], colors=colors, labels=labels) plt.title('CA') plt.legend(loc='upper left') plt.subplot(222) colors = [ '#000000', '#666633', '#003333', '#663333', '#000066', '#006600', '#CCCC99', '#336666', '#660099', '#CD6600' ] labels = [
# stack up dispatch and unmet demand # generation dispatched to meet demand = dispatch_technology * (1 - r) dispatch_mix = np.vstack([ dispatch_wind * (1 - r), dispatch_solar * (1 - r), dispatch_natgas * (1 - r), dispatch_storage, unmet_demand ]) dispatch_mix_c = np.vstack([ dispatch_wind_c * (1 - r_c), dispatch_solar_c * (1 - r_c), dispatch_natgas_c * (1 - r_c), dispatch_storage_c, unmet_demand_c ]) # plot # ax = fig.add_subplot(4,2,i+1) # ax[coords[ix]].stackplot(cost_unmet_demand, dispatch_mix, colors=colors) # plt.sca(ax[coords[ix]]) plt.stackplot(cost_unmet_demand, dispatch_mix, colors=colors) # ------------------------------------------------------------------------- # plot settings # axes # ax[coords[ix]].set_xlim(min(cost_unmet_demand), max(cost_unmet_demand)) # ax[coords[ix]].set_xscale('log') # ax[coords[ix]].xaxis.set_major_formatter(FormatStrFormatter('%.6g')) # ax[coords[ix]].set_ylim(0,1) # ax[coords[ix]].set_yticks([0,0.2,0.4,0.6,0.8,1]) # ax[coords[ix]].yaxis.set_major_formatter(FormatStrFormatter('%.2g')) # # reference for disabling minor ticks: # # https://stackoverflow.com/questions/10781077/how-to-disable-the-minor-ticks-of-log-plot-in-matplotlib # plt.minorticks_off() #
def drawKDE(y, t, y95b, y95u): plt.stackplot(t, y) plt.ylim(ymin=0) plt.show()
'/Users/iMac/Projects/u3179194_11069_Project2_Visualisation/Python Market Cap Chart/coin-dance-market-cap-historical.csv' ) data['Date'] = pd.to_datetime(data['Label']) data.sort_values('Date', inplace=True) marketCap_date = data['Date'] Bitcoin_Market_Cap = data['Bitcoin'] Altcoin_Market_Cap = data['Altcoins'] labels = ['Altcoins', 'Bitcoin'] colors = ['#e5ae37', '#6d904f'] plt.stackplot(marketCap_date, Altcoin_Market_Cap, Bitcoin_Market_Cap, labels=labels, colors=colors) plt.gcf().autofmt_xdate() plt.legend(loc='upper left') plt.ylabel('Market Cap (USD)') plt.xticks(rotation='-70', ha='left') plt.ticklabel_format(axis='y', style="sci") # or style = "plain" plt.title("Bitcoin Dominance") plt.tight_layout() plt.show() # Colors:
performance_tmp['fp_comp'] = fp_comp performance_tmp['t_online'] = cnm.t_online performance_tmp['comp_upd'] = cnm.comp_upd performance_tmp['t_el'] = t_el performance_tmp['t_online'] = cnm.t_online performance_tmp['comp_upd'] = cnm.comp_upd performance_tmp['t_detect'] = cnm.t_detect performance_tmp['t_shapes'] = cnm.t_shapes performance_tmp['CCs'] = xcorrs all_results[params_movie[ind_dataset]['folder_name']] = performance_tmp # %% Plot Timing performance if plot_results: plt.figure() plt.stackplot( np.arange(len(cnm.t_detect)), 1e3 * np.array(cnm.t_online) - np.array(cnm.t_detect) - np.array(cnm.t_shapes), 1e3 * np.array(cnm.t_detect), 1e3 * np.array(cnm.t_shapes)) plt.title('Processing time per frame') plt.xlabel('Frame #') plt.ylabel('Processing time [ms]') plt.ylim([0, 100]) plt.legend(labels=['process', 'detect', 'shapes']) if save_results: path_save_file = os.path.join( base_folder, 'results_CaImAn_Online_' + str(ID[0]) + '.npz') np.savez(path_save_file, all_results=all_results) # %% The variables ALL_CCs and all_results contain all the info necessary to create the figures print([[k, r['f1_score']] for k, r in all_results.items()])
# In[3 area plot] import matplotlib.pyplot as plt days = [1,2,3,4,5] sleeping =[7,8,6,11,7] eating = [2,3,4,3,2] working =[7,8,7,2,2] playing = [8,5,7,8,13] plt.plot([],[],color='m', label='Sleeping', linewidth=5) plt.plot([],[],color='c', label='Eating', linewidth=5) plt.plot([],[],color='r', label='Working', linewidth=5) plt.plot([],[],color='k', label='Playing', linewidth=5) plt.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k']) plt.xlabel('x') plt.ylabel('y') plt.title('Area Plot') plt.legend() plt.show() # In[3 Pie] import matplotlib.pyplot as plt days = [1,2,3,4,5] sleeping =[7,8,6,11,7] eating = [2,3,4,3,2] working =[7,8,7,2,2]
### Stacked Plot plt.style.use("fivethirtyeight") minutes = [1, 2, 3, 4, 5, 6, 7, 8, 9] player1 = [1, 2, 3, 3, 4, 4, 4, 4, 5] player2 = [1, 1, 1, 1, 2, 2, 2, 3, 4] player3 = [1, 1, 1, 2, 2, 2, 3, 3, 3] labels = ['player1', 'player2', 'player3'] colors = ['#6d904f', '#fc4f30', '#008fd5'] plt.stackplot(minutes, player1, player2, player3, labels=labels, colors=colors) plt.legend(loc='upper left') plt.title("Stacked Plot") plt.tight_layout() plt.show() ### Histogram import random import numpy as np # grades = [random.randint(0,100) for i in range(1000)] grades = np.random.normal(85, 13, 10000)
ibb_rep2quart.append(temp_rep_ibb) ibb_bounty2quart.append(temp_bounty_ibb) rest_rep2quart.append(temp_rep_rest) rest_bounty2quart.append(temp_bounty_rest) n = len(ibb_rep2quart) x = range(len(ibb_rep2quart)) width = 1 / 2 pal = sns.color_palette("Paired", 12) fig = plt.figure() ax = fig.add_subplot(1, 2, 1) ## Create bars plot h = plt.stackplot(x, [ibb_bounty2quart, rest_bounty2quart], colors=pal, alpha=0.9) plt.xticks(np.arange(0, n), quartersx, rotation="vertical") labeltext = 'Amount ratio' fontP = FontProperties() fontP.set_size('small') plt.ylabel(labeltext) plt.xlabel('Quarter') #plt.tight_layout() carlosplt.post_paper_plot(True, True, True) #plt.show() # In[20]: ax = fig.add_subplot(1, 2, 2)
pal = sns.color_palette("Set2") print("Vector Lengths: %d, %d" % (len(y[0]), len(daterange))) date_form = DateFormatter("%Y") plot.xaxis.set_major_locator(matplotlib.dates.YearLocator(1)) plot.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y')) plot.xaxis.set_minor_locator(matplotlib.dates.MonthLocator((1, 4, 7, 10))) plot.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("\n%Y")) plot.xaxis.set_minor_formatter(matplotlib.dates.DateFormatter("%b")) print(daterange[0]) print(daterange[len(daterange) - 1]) plot.set_xlim(pd.to_datetime(daterange[0]), pd.to_datetime(daterange[len(daterange) - 1])) plt.setp(plot.get_xticklabels(), rotation=0, ha="center") plot.xaxis.set_major_formatter(date_form) #plot.stackplot(daterange,y) plt.grid() #plt.gca().yaxis.set_ticklabels([]) plt.stackplot(daterange, y, colors=pal, alpha=0.8) #plt.tick_params(labelbottom='off') #plt.tick_params(labelleft='off') #plt.show() #plugins.connect(plt.figure()) mpld3.show()
import matplotlib.pyplot as plt # 处理中文乱码 plt.rcParams['font.sans-serif'] = ['SimHei'] x_data = [2011, 2012, 2013, 2014, 2015, 2016, 2017] y_data = [58000, 60200, 63000, 71000, 84000, 90500, 107000] y_data_1 = [78000, 80200, 93000, 101000, 64000, 70500, 87000] plt.title(label='xxx 公司 xxx 产品销量') plt.stackplot(x_data, y_data, y_data_1, labels=['产品销量', '用户增长数']) plt.legend() plt.savefig("stackplot_demo.png")
def drawKDE(opty) : plt.stackplot(range(0, 200), opty) plt.ylim(ymin = 0) plt.show()
def classifier_costs(fig=None, title=None, admin_cost=[5], mask=None, scenarios=None, rows=None, columns=None): '''calculates average fraud costs associated with different thresholds of the model''' '''loss occurs for false negative scenario''' loss_matrix = np.array([[0, 0], [1, 0]]) n_scenarios = len(scenarios) n_costs = len(admin_cost) f = plt.figure(num=fig, figsize=(columns * 12, rows * 12)) f.suptitle( 'Fig. {}: {} '.format(fig, title), fontsize=26) ct = 0 axes = [] for n, s in enumerate(scenarios): ytest, probas, purchase_test = classifier(s[1]) for cost in admin_cost: ct += 1 thresholds = [.1, .2, .3, .4, .5, .6, .7, .8, .9, 1] losses = [] admin_costs = [] total_costs = [] '''admin costs incurred for any positive prediction''' admin_cost_matrix = np.array([[0, cost], [0, cost]]) for threshold in thresholds: ypredict = (probas > threshold).astype(int) confusion = np.stack([ytest, ypredict], axis=0) print (confusion) loss_calc = loss_matrix[confusion[0, :], confusion[1, :]] * purchase_test admin_calc = admin_cost_matrix[confusion[0, :], confusion[1, :]] avg_loss = np.mean(loss_calc) avg_admin_cost = np.mean(admin_calc) total_loss = avg_loss + avg_admin_cost losses.append(avg_loss) admin_costs.append(avg_admin_cost) total_costs.append(total_loss) print (thresholds) print (losses) print (admin_costs) print (total_costs) ax = f.add_subplot(rows, columns, ct) plt.stackplot(thresholds, [losses, admin_costs], baseline='zero', labels=['direct fraud costs', 'admin costs'], alpha=.6) plt.title(s='{}\n${:.2f} admin cost/incident'.format(s[0], cost), fontsize=20) plt.xlabel('Classifier Threshold ', fontsize=16) plt.xticks(fontsize=16) plt.yticks(fontsize=16) plt.ylabel('Cost per Customer $', fontsize=16) plt.legend(fontsize=16) xpoint = thresholds[np.argmin(total_costs)] ypoint = min(total_costs) # plt.annotate('', xy=(xpoint, ypoint), xytext=(xpoint + .1, ypoint + 2), arrowprops=dict(facecolor='black', shrink=0.05, connectionstyle='arc3'), fontsize=16 ) bbox_props = dict(boxstyle="round4,pad=0.4", fc="yellow", ec="b", lw=3, alpha=1) t = ax.text(xpoint + .1, ypoint + 2.2, "Minimum Cost ${:.2f}".format(ypoint), ha="center", va="center", rotation=0, size=18, fontsize=18, bbox=bbox_props) plt.subplots_adjust(hspace=.4) plt.show()
def plot(filename, title, counts, dates, top_n=20): """Makes a stacked line plot of contributions over time. Plot will be stored in PDF named ``filename``, with the given ``title``, using data in ``counts`` and ``dates``. ``counts`` is a list of dictionaries, each mapping the contributor name (author, organization, etc.) to line count for a commit. ``dates`` is a list of dates, for the commits. The two lists should be the same length. The stacked plots will explicitly show data for the top N contributors. N defaults to 20. """ # Sort data ascending by date. sorted_list = sorted(zip(dates, counts)) dates, counts = zip(*sorted_list) # Get sorted lists of top contributors (by line) from the last commit. contributors = sorted(counts[-1].keys(), key=lambda c: counts[-1][c]) top_contributors = contributors[-top_n:] labels = top_contributors # List of series, one for each top contributor. Each element is a # count for a commit. series = [[cdict.get(c, 0) for cdict in counts] for c in top_contributors] # List of summed line counts from "other", non-top contributors other = [ sum(count for c, count in cdict.items() if c not in top_contributors) for cdict in counts ] if other: series.insert(0, other) labels = ["Other"] + labels # Use a nice color scheme. cm = plt.get_cmap("Paired") c_norm = matplotlib.colors.Normalize(vmin=0, vmax=len(series) - 1) scalar_map = cmx.ScalarMappable(norm=c_norm, cmap=cm) # Try to add contrast by shuffling the initially smooth-ish gradient. nc = len(series) colors = [scalar_map.to_rgba(i + 1) for i in range(nc)] colors.reverse() colors = colors[::3] + colors[1::3] + colors[2::3] plt.figure(figsize=(8, 4), dpi=320) plt.title(title) # Do the plot plt.stackplot(dates, series, labels=labels, lw=0, colors=colors) locs, labels = plt.xticks() plt.setp(labels, rotation=45) # Set up a legend with contributor names ax = plt.gca() handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], ncol=3, fontsize=10, loc="upper left") plt.tight_layout() plt.savefig(filename)
#Run Cell ou Run Below #%% #Módulos import matplotlib.pyplot as plt #Número de meses mes = [1, 2, 3, 4, 5, 6] #Quantidade de produtos vendidos loja_1 = [100, 120, 80, 300, 200, 50] loja_2 = [250, 90, 60, 150, 300, 290] loja_3 = [40, 30, 60, 190, 250, 20] #Criação do gráfico #Valores do x e dos y e indicação de que a que cor corresponde cada loja plt.stackplot(mes, loja_1, loja_2, loja_3, labels=['Loja 1', 'Loja 2', 'Loja 3']) #Título plt.title("Grafico") #Texto para a zona do x plt.xlabel("Mes") #Texto para a zona do y plt.ylabel("Quantidade vendida") #Indicação que queremos colocar a legenda (Nome das lojas e a sua respetiva cor) plt.legend(loc='upper left') #Visualizar a tabela plt.show # %%
plt.title('Diagram Titik') plt.legend() plt.show() #%% Stack Plot hari = [1, 2, 3, 4, 5, 6, 7] tidur = [7, 8, 6, 8, 7, 9, 10] makan = [2, 3, 4, 3, 2, 3, 4] kerja = [7, 8, 7, 2, 2, 6, 0] main = [8, 5, 7, 8, 13, 15, 25] plt.plot([], [], color='m', label='Tidur', linewidth=5) plt.plot([], [], color='c', label='Makan', linewidth=5) plt.plot([], [], color='r', label='Kerja', linewidth=5) plt.plot([], [], color='k', label='Main', linewidth=5) plt.stackplot(hari, tidur, makan, kerja, main, colors=['b', 'm', 'r', 'c']) plt.xlabel('Hari') plt.ylabel('Lamanya') plt.title('Stack Plot') plt.legend() plt.show() #%% Subplot x = [1, 2, 3, 4, 5] y = [6, 7, 8, 9, 10] plt.subplot(331) #tinggi,lebar,urutan plt.plot(x, y) plt.subplot(332) plt.bar(x, y) plt.subplot(333) plt.hist(x, 2)
def plotData(args, axes=None): if not axes: axes = [] else: axcount = 0 args = parser.parse_args(args) IndepVars = args.IV DepVars = args.DV slicedVars = [] for i in range(len(args.SV)): slicer = args.SV[i].split('=') if slicer[0] in IndepVars: raise ValueError('sliced variables cannot independent variables') slicedVars.append((slicer[0], float(slicer[1]))) projectNames = args.DataSetName if projectNames[0] == 'PlotData.py': projectNames.pop(0) #DataFrames = [] for pN in projectNames: if pN.endswith('.df'): with open('results/{}'.format(pN), 'r') as f: DataFrame = pickle.load(f) elif pN.endswith('.csv'): DataFrame = pandas.read_csv('results/{}'.format(pN)) else: raise ValueError("projectName {} invalid".format(pN)) if "phi" in DataFrame.columns: df_phis = np.unique(DataFrame.phi.values) for sv in slicedVars: if sv[0] == 'phi': phi = sv[1] if phi == 90.0 and phi not in df_phis: DataFrame.loc[DataFrame.phi.values == 30.0, 'phi'] = 90.0 DFNames = DepVars Alliases = DepVars DimensionNames = IndepVars Dimensions = {} DFCols = list(DataFrame) ''' UnusedVars = [] for i in range(len(DFCols)): if not any(ext in DFCOls[i] for ext in IndepVars): UnusedVars.append(DFCols[i]) ''' for i in range(len(DimensionNames)): dimensionNumpy = DataFrame[DimensionNames[i]].values uniqueNumpy = np.unique(dimensionNumpy) Dimensions[DimensionNames[i]] = uniqueNumpy #Dimensions['vacuum_wavelengths'] = np.arange(400,710,10)*1e-9 #Dimensions['theta'] = np.arange(0.0,82.5,2.5) #Dimensions['phi'] = np.array([0.,45.0]) DimensionLengths = [] for i in range(len(DimensionNames)): DimensionLengths.append(len(Dimensions[DimensionNames[i]])) Arrays = {} for i in range(len(Alliases)): Arrays[Alliases[i]] = np.zeros(DimensionLengths) #print(slicedVars) #print(DataFrame.head(5)) DataFrame = SliceDataFrame(DataFrame, slicedVars) CreateArrays(DataFrame, copy.copy(IndepVars), Arrays, DFNames, Alliases, DimensionLengths) if len(Dimensions) == 1: if axes is None: f, ax = plt.subplots() axes.append(ax) else: plt.sca(axes[axcount]) axcount += 1 ''' 1-D Data ''' if IndepVars[0] == 'vacuum_wavelength': Dimensions[IndepVars[0]] *= 1e9 if args.averageDVs == False and args.sumDVs is False: if args.stacked: stackedData = np.zeros( (len(DepVars), Dimensions[IndepVars[0]].size)) plotLabels = [] iDV = 0 for dv in DepVars: if args.logy: #plt.semilogy(Dimensions[IndepVars[0]],Arrays[dv],'o') plt.semilogy(Dimensions[IndepVars[0]], np.power(10, Arrays[dv])) elif args.loglog: plt.loglog(Dimensions[IndepVars[0]], Arrays[dv]) else: if args.stacked: stackedData[iDV, :] = Arrays[dv] plotLabels.append(dv) iDV += 1 else: plt.plot(Dimensions[IndepVars[0]], Arrays[dv]) if args.stacked: plt.stackplot(Dimensions[IndepVars[0]], stackedData, labels=plotLabels) else: y = np.zeros(Arrays[DepVars[0]].shape) for dv in DepVars: if args.averageDVs: y += Arrays[dv] / len(DepVars) elif args.sumDVs: y += Arrays[dv] if args.logy: plt.semilogy(Dimensions[IndepVars[0]], np.power(10, y)) elif args.loglog: plt.loglog(Dimensions[IndepVars[0]], y) else: plt.plot(Dimensions[IndepVars[0]], y) plt.grid(True) plt.xlabel(IndepVars[0]) plt.ylabel(DepVars[0]) if args.savefig: plt.savefig('figures/{}.pdf'.format(".".join( projectNames[0].split('.')[0:-1]))) if args.display_max: print(np.max(Arrays[DepVars[0]])) print(Dimensions[IndepVars[0]][np.argmax(Arrays[DepVars[0]])]) if 'DISPLAY' in os.environ and not args.noplot: plt.show() elif len(Dimensions) == 2: #[X,Y] = np.meshgrid( Dimensions[IndpVars[0]], Dimensions[IndpVars[1]]) if IndepVars[0] == 'vacuum_wavelength': Dimensions[IndepVars[0]] *= 1e9 if IndepVars[1] == 'vacuum_wavelength': Dimensions[IndepVars[1]] *= 1e9 xmin = np.min(Dimensions[IndepVars[0]]) xmax = np.max(Dimensions[IndepVars[0]]) ymin = np.min(Dimensions[IndepVars[1]]) ymax = np.max(Dimensions[IndepVars[1]]) X, Y = np.meshgrid(Dimensions[IndepVars[0]], Dimensions[IndepVars[1]]) Extent = (xmin, xmax, ymin, ymax) if args.averageDVs == False and args.sumDVs == False: for dv in DepVars: if axes is None: f, ax = plt.subplots() axes.append(ax) else: plt.sca(axes[axcount]) axcount += 1 #plt.imshow(np.transpose(Arrays[dv]),extent=Extent,aspect='auto',origin='lower') if args.logy: z = np.log10(np.transpose(Arrays[dv][:-1, :-1])) else: z = np.transpose(Arrays[dv][:-1, :-1]) plt.pcolormesh(X, Y, z) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) #range(np.shape(Arrays[dv])[0]): if args.savefig: #print pN #print pN.split('.') #print pN.split('.')[0:-1] #print ".".join(projectNames[0].split('.')[0:-1]) plt.savefig('figures/{}_{}.pdf'.format( ".".join(projectNames[0].split('.')[0:-1]), dv)) if 'DISPLAY' in os.environ and not args.noplot: plt.show() else: z = np.zeros(Arrays[DepVars[0]].shape) for dv in DepVars: z_contribution = Arrays[dv] if args.exponentiateDVs: z_contribution = np.power(10, z_contribution) if args.averageDVs: z += z_contribution / len(DepVars) elif args.sumDVs: z += z_contribution if not axes: f, ax = plt.subplots() axes.append(ax) else: plt.sca(axes[0]) #plt.imshow(np.transpose(z),extent=Extent,aspect='auto',origin='lower') if args.exponentiateDVs: z = np.log10(z) plt.pcolormesh(X, Y, np.transpose(z[:-1, :-1])) plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) #range(np.shape(Arrays[dv])[0]): if args.savefig: #print pN #print pN.split('.') #print pN.split('.')[0:-1] #print ".".join(projectNames[0].split('.')[0:-1]) plt.savefig('figures/{}_{}.pdf'.format( ".".join(projectNames[0].split('.')[0:-1]), dv)) if 'DISPLAY' in os.environ and not args.noplot: plt.show()
''' @Author:Yohannes Assebe(John Assebe) github stack plot ''' from matplotlib import pyplot as plt import pandas as pd plt.style.use('fivethirtyeight') df = pd.read_csv('../percent_bachelors_degrees_women_usa.csv') cols = df.columns.values # list of columns name assigned to cols plt.stackplot( df[cols[0]], # Assign values for x-value df[cols[1]], df[cols[2]], df[cols[3]], # list of column values Forexample df[cols[1]]=df['Agriculture'] labels=[cols[1], cols[2], cols[3]]) plt.xlabel("Year") plt.ylabel('Total') plt.title("Women bachelor degree percents in USA") plt.legend(loc='upper left') # plt.tight_layout() plt.show()
plot2 = figure.add_subplot(1, 2, 1) plot2.plot(gT, ((gM + gG).T + np.arange(totalPoint_X) * 1000)) plt.title(r'$ Antibody \ Response $', fontsize=AlvaFontSize) plt.xlabel(r'$time \ ({:})$'.format(timeUnit), fontsize=AlvaFontSize) plt.ylabel(r'$ discrete \ space \ (strain) $', fontsize=AlvaFontSize) figure.tight_layout() plt.show() # In[5]: # Normalization stacked graph numberingFig = numberingFig + 1 plt.figure(numberingFig, figsize=AlvaFigSize) plt.stackplot(gT, gM + gG, alpha=0.3) plt.title(r'$ Stacked-graph \ of \ Antibody $', fontsize=AlvaFontSize) plt.xlabel(r'$time \ ({:})$'.format(timeUnit), fontsize=AlvaFontSize) plt.ylabel(r'$ Neutralization \ \ titer $', fontsize=AlvaFontSize) plt.xticks(fontsize=AlvaFontSize * 0.6) plt.yticks(fontsize=AlvaFontSize * 0.6) plt.ylim([2**0, 2**15]) plt.yscale('log', basey=2) plt.grid(True) plt.show() # In[6]: # expected peak of the antibody response totalColor = current_virus - origin_virus + 1 AlvaColor = [
explode=explode, shadow=True, startangle=180, autopct="%1.1f%%") plt.show() # In[9]: minutes = [1, 2, 3, 4, 5] player1 = [2, 3, 1, 2, 3] player2 = [1, 4, 2, 3, 4] player3 = [2, 1, 4, 2, 3] labels = ['player1', 'player2', 'player3'] plt.stackplot(minutes, player1, player2, player3, labels=labels) plt.legend(loc="upper left") plt.show() # In[10]: from datetime import datetime, timedelta from matplotlib import dates as mpl_dates # In[11]: plt.style.use('seaborn') dates = [ datetime(2019, 1, 1), datetime(2019, 1, 2), datetime(2019, 1, 3),
############################################################################### # And extract population information (and check total is right) population = data.loc[zones]['Population, total'].swaplevel().unstack() population = population[zones] assert all(data.loc['World']['Population, total'] == population.sum(axis=1)) ############################################################################### # ## Stacked area plot with matplotlib import matplotlib.pyplot as plt "" plt.clf() plt.figure(figsize=(10, 5), dpi=100) plt.stackplot(population.index, population.values.T / 1e9) plt.legend(population.columns, loc='upper left') plt.ylabel('Population count (B)') plt.show() ############################################################################### # ## Stacked bar plot with plotly import plotly.offline as offline import plotly.graph_objs as go offline.init_notebook_mode() "" data = [ go.Scatter(x=population.index,
def initialise_window(board): window = tk.Tk() log.info("Initialising GUI") window.title("MATH-4076 Project") cells = tk.Frame(window, relief=tk.RAISED, bd=2) for i in range(len(board.board)): cells.columnconfigure(i, weight=1, minsize=5) cells.rowconfigure(i, weight=1, minsize=5) for j in range(len(board.board[i])): frame = tk.Frame(master=cells, relief=tk.RAISED, borderwidth=1) frame.grid(row=i, column=j + 1) text_display = tk.StringVar() label = tk.Label(master=frame, textvariable=text_display, width=3, font=(None, 8), fg='white', bg=_color_map[board.board[i][j].state]) text_display.set(board.board[i][j].state) board.board[i][j].associate_cell(label) board.board[i][j].associate_text_cell(text_display) label.pack() fig = plt.figure(1) plt.ion() x = range(1, 1 + len(board.SIR_data['S'])) y = [board.SIR_data['I'], board.SIR_data['S'], board.SIR_data['R']] plt.stackplot(x, y, labels=['I', 'S', 'R'], colors=['tab:red', 'tab:green', 'black']) board.add_fig(fig) canvas = FigureCanvasTkAgg(fig, master=window) plot_widget = canvas.get_tk_widget() plot_widget.grid(row=0, column=2) buttons = tk.Frame(master=window, relief=tk.RAISED, bd=2) btn_run = tk.Button(buttons, text="Run", font=(None, 10), command=lambda: run_sim(board, False)) btn_run.grid(row=0, column=0, sticky="ew", padx=5, pady=5) board.add_button(btn_run) btn_reset = tk.Button(buttons, text="Reset", font=(None, 10), command=lambda: reset(board, fig)) btn_reset.grid(row=2, column=0, sticky="ew", padx=5, pady=5) btn_step = tk.Button(buttons, text="Step", font=(None, 10), command=lambda: run_sim(board, True)) btn_step.grid(row=1, column=0, sticky="ew", padx=5, pady=5) btn_cfg = tk.Button(buttons, text="Config", font=(None, 10), command=lambda: launch_config(window, board)) btn_cfg.grid(row=3, column=0, sticky="ew", padx=5, pady=5) def exit_program(): window.quit() btn_exit = tk.Button(buttons, text="Exit", font=(None, 10), command=exit_program) btn_exit.grid(row=4, column=0, sticky="ew", padx=5, pady=5) buttons.grid(row=0, column=0, sticky="ns") cells.grid(row=0, column=1) window.mainloop()
sigma_gmv = 1.0 / np.sqrt(C) sigma_p = np.linspace(sigma_gmv, 1.05 * np.max(Stdev), num=250) mu_p_efficient = (A + np.sqrt(np.abs(C * sigma_p**2 - 1.0) * D)) / C fig1 = plt.figure(1, facecolor='w') plt.plot(sigma_p, mu_p_efficient, 'k-') plt.plot(V_Risk, V_Target, 'k:') plt.plot(np.sqrt(np.diagonal(Sigma)), Mu, 'kx') plt.legend([u'最小分散フロンティア(空売り制約なし)', u'最小分散フロンティア(空売り制約あり)', u'個別資産'], loc='best', frameon=False, prop=jpfont) plt.xlabel(u'標準偏差(%)', fontproperties=jpfont) plt.ylabel(u'期待収益率(%)', fontproperties=jpfont) # 投資比率の推移の作図 fig2 = plt.figure(2, facecolor='w') plt.stackplot(V_Target, V_Weight.T * 100, colors=tuple([ tuple(gray * np.ones(3)) for gray in np.linspace(0.4, 0.8, num=Mu.shape[0]) ])) plt.axis([Mu.min(), Mu.max(), 0.0, 100.0]) plt.legend([u'資産1', u'資産2', u'資産3', u'資産4', u'資産5'], loc='upper left', bbox_to_anchor=(1.0, 1.0), frameon=False, prop=jpfont) plt.xlabel(u'目標期待収益率(%)', fontproperties=jpfont) plt.ylabel(u'投資比率(%)', fontproperties=jpfont) plt.show()