def main(): __handdrawn__ = True if __handdrawn__: from matplotlib import pyplot as plt plt.xkcd() ohms = circuit.Circuit('resources/node_voltage.crt') ohms.create_nodes() ohms.populate_nodes() ohms.identify_nontrivial_nodes() ohms.create_branches() ohms.create_supernodes() ohms.sub_super_nodes() ohms.identify_nontrivial_nonsuper_nodes() # TODO some of these should be moved to solver later schem = drawer.Schematic(ohms) schem.draw_schem() my_solution = solver.Solver(ohms) my_solution.set_reference_voltage(my_solution.circuit.non_trivial_reduced_nodedict[0]) my_solution.identify_voltages() my_solution.identify_currents() #print("performing kcl at each of the nodes in the circuit:") #todo move to solver #ohms.kcl_everywhere() #ohms.ohms_law_where_easy() my_solution.gen_node_voltage_eq() #ohms.sub_zero_for_ref() my_solution.determine_known_vars() my_solution.sub_into_eqs() my_solution.solve_subbed_eqs() #print(ohms.nodelist) #print(ohms.num_nodes) #print(ohms.netlist) vivias = solver.Teacher(my_solution) vivias.explain()
def frequency_power_plot(frequency, power, max_x, max_y, save_to): plt.close() star_label = 'Highest power: {0}db, corresponding frequency value: {1}hz'.format(int(max_y), int(max_x)) #create subplots ax1 and ax2 plt.xkcd() f, (ax1, ax2) = plt.subplots(2) plt.xlabel('Frequency(hz)', color='#4B0082') plt.ylabel('Power(db)', color='#4B0082') #plot axis1 ax1.set_title('Frequency-Power plot', color='#4B0082') ax1.plot(frequency, power, label='Power', color='#FF69B4') ax1.plot(max_x, max_y, '*', label=star_label, color='#FF7F00') legend = ax1.legend(loc='lower center', shadow=True, fontsize='x-small') # legend.get_frame().set_facecolor('#FF69B4') #plot axis2 ax2.plot(frequency, power, label='Power', color='#FF69B4') ax2.plot(max_x, max_y, '*', label=star_label, color='#FF7F00') ax2.set_xlim([(max_x - 50), (max_x + 50)]) legend = ax2.legend(loc='lower center', shadow=True, fontsize='x-small') # legend.get_frame().set_facecolor('') plt.savefig(save_to)
def makePlot (filename, xkcd, data): import numpy as np import matplotlib import matplotlib.pyplot as plt x=[m[0] for m in data] stay = [m[1] for m in data] spin = [m[2] for m in data] fig = plt.figure() if xkcd: plt.xkcd() # uncomment for xkcd style plots fig.suptitle("Price is Right Spin Strategy", fontsize=14, fontweight='bold') ax = plt.subplot(111) # get default subplot to make it nice ax.set_ylim(0,100) # force the % to be 0-100 ax.set_xlim(0,100.1) # force a grid line at 100 ax.grid(True) # turn on the grid ax.spines['top'].set_visible(False) # turn off top part of box (top spine) ax.spines['right'].set_visible(False) # turn off right part of box (right spine) ax.yaxis.set_ticks_position('left') # turn off tick marks on right ax.xaxis.set_ticks_position('none') # turn off tick marks on top and bottom ax.set_xticks(range(0,110,10)) # set ticks to be by 10s ax.set_yticks(range(0,110,10)) # set ticks to be by 10s plt.plot(x,stay,color="b",label="stay") plt.plot(x,spin,color="r",label="spin again") plt.fill_between(x,0,stay,alpha=0.2,color='b') plt.fill_between(x,0,spin,alpha=0.2,color='r') plt.ylabel("% chance of winning") plt.xlabel("first spin result") plt.legend(loc=2) # 2=upper-left (see pydoc matplotlib.pyplot.legend) fig.savefig(filename, format="png")
def makeFig(data=None, scaleFactor=1, datarate=3200): """ prints the acquired data """ if docArgs['--xkcd']: plt.xkcd() time = len(data)/float(datarate) fig, ax1 = plt.subplots() ax1.axis('auto') plt.ylabel("Acceleration (g)") plt.xlabel("Time (s)") ax1.grid(True) try: timestep = np.linspace(0,time,len(data)) ax1.plot(timestep, [dat[0] for dat in data], 'r-', label='X Axis Values', lw=0.5) ax1.plot(timestep, [dat[1] for dat in data], 'b-', label='Y Axis Values', lw=0.5) ax1.plot(timestep, [dat[2] for dat in data], 'g-', label='Z Axis Values', lw=0.5) except: data = np.delete(data,0,0) timestep = np.linspace(0,time,len(data)) #data2 = np.trapz(data[:,0]) ax1.plot(timestep, [dat[0] for dat in data], 'r-', label='X Axis Values', lw=0.5) ax1.plot(timestep, [dat[1] for dat in data], 'b-', label='Y Axis Values', lw=0.5) ax1.plot(timestep, [dat[2] for dat in data], 'g-', label='Z Axis Values', lw=0.5) ax2 = ax1.twinx() #ax2.plot(timestep, velocity, 'k-', label='Velocity', lw=0.5) ax1.legend(loc='lower right') plt.show()
def initialize(self): self.figure = matplotlib.figure.Figure(facecolor='white') self.axes = self.figure.add_subplot(111, xlim=(0,4), ylim=(0, 1), ybound=[0, 1]) plt.xkcd() self.axes.spines['right'].set_color('none') self.axes.spines['top'].set_color('none') self.axes.set_xticks([]) self.axes.set_yticks([]) self.axes.set_ybound(lower=0, upper=1) probabs = [0.3, 0.3, 0.3] xlabels = ['R', 'P', 'S'] self.axes.bar([1, 2, 3], probabs, align='center', color='lightskyblue') for i in range(3): self.axes.text(i+1, probabs[i] + 0.01, '%.2f' % probabs[i], ha='center', va='bottom') self.axes.text(i+1, probabs[i] - 0.05, xlabels[i], ha='center', va='top') for i in range(2, 11, 2): self.axes.text(-0.1, i/10.0, str(i/10.0), ha='right', va='center') self.axes.set_title('Probability distribution') self.canvas = FigureCanvas(self, -1, self.figure)
def main(): # xkcd-ify everything, use the Qt4Agg backend (osx backend does not work) plt.switch_backend('Qt4Agg') plt.xkcd() # set up figure and axes for results fig, ax = plt.subplots(2, 2) # compare dogs and cats exact = False N1 = getNResults('dogs are better than cats', exact) N2 = getNResults('cats are better than dogs', exact) MakePlot(ax[0, 0], N1, N2) # is global warming real or fake N3 = getNResults('global warming is real', exact) N4 = getNResults('global warming is fake', exact) MakePlot(ax[0, 1], N3, N4) # compare bud light and miller lite N5 = getNResults('bud light is better than miller lite', exact) N6 = getNResults('miller lite is better than bud light', exact) MakePlot(ax[1, 0], N5, N6) # compare GW Bush N7 = getNResults('George Bush is the Worst President Ever', exact) N8 = getNResults('George Bush is the Best President Ever', exact) MakePlot(ax[1, 1], N7, N8) # clean up and show plt.subplots_adjust(hspace = 0.4) plt.show()
def plot_worth_vs_time(self, names=None): if names is None: names = [ 'Investor ({:0.2f},{:0.2f})'.format(inv.buy_at, inv.sell_at) for inv in self.investors] dates = [x[0] for x in self.pe_array] year = YearLocator() date_fmt = DateFormatter('%Y') plt.xkcd() # investor worth plots fig = plt.figure() ax = fig.gca() lines = [] for i in range(len(self.investors)): result = ax.plot_date(dates, self.worth_matrix[i], '-') lines.append(result[0]) ax.xaxis.set_major_locator(year) ax.xaxis.set_major_formatter(date_fmt) # ax.xaxis.set_minor_formatter(MonthLocator()) ax.autoscale_view() ax.legend(lines, names, 'upper left') fig.autofmt_xdate() fig_pe = plt.figure() ax_pe = fig_pe.gca() ax_pe.plot_date(dates, [x[1] for x in self.pe_array], '-') ax_pe.xaxis.set_major_locator(year) ax_pe.xaxis.set_major_formatter(date_fmt) ax_pe.autoscale_view() ax_pe.set_title('PE Ratio vs. Time') fig_pe.autofmt_xdate() plt.show()
def __init__(self, timelines, custom, showWindow=True, registry=None): """:param timelines: The timelines object :type timelines: TimeLineCollection :param custom: A CustomplotInfo-object. Values in this object usually override the other options """ MatplotlibTimelines.__init__(self, timelines, custom, showWindow=showWindow, registry=registry ) from matplotlib import pyplot try: pyplot.xkcd() except AttributeError: from matplotlib import __version__ warning("Installed version",__version__, " of Matplotlib does not support XKCD-mode (this is supported starting with version 1.3). Falling back to normal operations")
def api_membership_graph(): from payments import membership import matplotlib import numpy as np matplotlib.use("Agg") import matplotlib.pyplot as plt from cStringIO import StringIO page=''' <html> <body> <img src="data:image/png;base64,{}"/> </body> </html> ''' plt.xkcd() fig = plt.figure() members = membership() members.reverse() counts = [x[2] for x in members] dates = [str(x[1])[-2:]+"/"+str(x[0]) for x in members] ax = plt.subplot(111) ax.bar(range(len(dates)),counts,width=1) ax.set_xticks(np.arange(len(dates))+.5) ax.set_xticklabels(dates, rotation=90) plt.xlabel('Date') plt.ylabel('Members') plt.subplots_adjust(bottom=0.15) io = StringIO() fig.savefig(io, format='png') data = io.getvalue().encode('base64') return page.format(data)
def plot_worth_vs_time(self, names=None): """Plot the worth of each investor vs. time. If names is specified, will use these names in the legend. Otherwise, will name the investors based off their thresholds. """ if names is None: names = [ 'Investor ({:0.2f},{:0.2f})'.format(inv.buy_at, inv.sell_at) for inv in self.investors] dates = [x[0] for x in self.pe_array] year = YearLocator() date_fmt = DateFormatter('%Y') plt.xkcd() # investor worth plots fig = plt.figure() ax = fig.gca() lines = [] for i in range(len(self.investors)): result = ax.plot_date(dates, self.worth_matrix[i], '-') lines.append(result[0]) ax.xaxis.set_major_locator(year) ax.xaxis.set_major_formatter(date_fmt) # ax.xaxis.set_minor_formatter(MonthLocator()) ax.autoscale_view() ax.legend(lines, names, 'upper left') fig.autofmt_xdate() return fig
def benchmark(datasize): """Plot the output of each benchmark to its own file""" for test in TESTS: data = [] labels = [] DATASTORES.sort() for datastore in DATASTORES: labels.append(datastore) if datastore_benchmarked(datasize, datastore): (_, values) = read_values(datasize, datastore, test) if test == 'BatchWrite': # Normalize batch measurement to 1 row values = [val/float(datasize) for val in values] values = [1.0e9/val for val in values] # Convert to ops/sec data.append(values) if XKCD_STYLE: plt.xkcd() # Plot API: http://matplotlib.org/1.3.1/api/pyplot_api.html # Box-and-Whisker plot with an IQR of 1.5 and hidden outliers. plt.title('Data stores comparison - ' + test) plt.ylabel('Ops/sec') plt.boxplot(data, whis=1.5, sym='') plt.xticks(np.arange(1, len(labels) + 1), labels) out_file_name = str(datasize) + '/benchmark_' + test +'.png' plt.savefig(out_file_name) plt.close()
def Make_Plot(Apzwn,Afreq): plt.xkcd() plt.figure() tw,nw = Apzwn.shape for i in range(tw): plt.plot(Apzwn[i,:],Afreq[i,:], linewidth=1,color='k') plt.text(3,0.15,'Kelvin', bbox={'facecolor':'white'}) plt.text(-12,0.04,'ER', bbox={'facecolor':'white'}) plt.text(-10,0.15,'MRG', bbox={'facecolor':'white'}) plt.text(3.5,0.37,'IG n=0', bbox={'facecolor':'white'}) plt.text(-2,0.45,'IG n=1', bbox={'facecolor':'white'}) plt.text(-2,0.57,'IG n=2', bbox={'facecolor':'white'}) plt.text(-2,0.68,'IG n=3', bbox={'facecolor':'white'}) plt.plot((0,0), (0,1),'--',linewidth=2,color='k') plt.text(10,-0.09,'Eastward') plt.text(-16,-0.09,'Westward') plt.xlabel('Zonal Wavenumber',size=13,fontweight='bold') plt.ylabel('Frequency (CPD)',size=13,fontweight='bold') texto = 'Matsuno Modes' plt.title(texto,size=15,fontweight='bold') plt.xlim((-20,20)) plt.ylim((0,1)) plt.savefig('Matsuno.png', format='png')
def main(): args = parse_args() # find top paths by size toppaths = nlargest_paths(args.csvpath, n=args.number) # pop the root so we don't graph 100% root = toppaths[0] rootpath = root[1] paths = toppaths[1:] sizes = np.array([p[0] for p in paths]) names = [p[1][len(rootpath) + 1:] for p in paths] dumpdata(rootpath, names, sizes) plt.xkcd() fig = plt.figure() ax = fig.gca() graymap = [mpl.cm.gray(v) for v in np.linspace(0.5,1,len(names))] plt.pie(sizes, labels=names, colors=graymap) plt.title('space used\n{}'.format(root)) ax.set_aspect('equal') plt.show()
def main(tend=2.0, A0=1.0, nt=67, t0=0.0, rates='3.40715,4.0'): k = list(map(float, rates.split(','))) n = len(k)+1 if n > 4: raise ValueError("Max 3 consequtive decays supported at the moment.") tout = np.linspace(t0, tend, nt) y0 = np.zeros(n) y0[0] = A0 Cref = get_Cref(k, y0, tout - tout[0]).reshape((nt, 1, n)) plt.xkcd() fig = plt.figure(figsize=(2, 2), dpi=100) ax = plt.subplot(1, 1, 1) for i, l in enumerate('ABC'[:n]): ax.plot(tout, Cref[:, 0, i], label=l, color='rbg'[i]) ax.xaxis.set_tick_params(width=1) ax.yaxis.set_tick_params(width=1) ax.set_xticks([0, 1, 2]) ax.set_yticks([0, 0.5, 1]) ax.set_facecolor((0.9, 0.9, 0.9)) fig.patch.set_facecolor((1.0, 1.0, 1.0, 0.0)) #ax.text(.35, 0.5, r'A $\rightarrow$ B $\rightarrow$ C', fontsize=9) plt.title('chemreac', fontsize=21) plt.legend(loc='best', prop={'size': 10}) plt.tight_layout() plt.savefig('chemreac_logo.svg', transparent=True) plt.savefig('chemreac_logo.png', transparent=True)
def setup_figure(self): """ Prepare the matplotlib figure for plotting. This method sets the default font, and the overall apearance of the figure. """ if options.cfg.xkcd: fonts = QtGui.QFontDatabase().families() for x in ["Humor Sans", "DigitalStrip", "Comic Sans MS"]: if x in fonts: self.options["figure_font"] = QtGui.QFont(x, pointSize=self.options["figure_font"].pointSize()) break else: for x in ["comic", "cartoon"]: for y in fonts: if x.lower() in y.lower(): self.options["figure_font"] = QtGui.QFont(x, pointSize=self.options["figure_font"].pointSize()) break plt.xkcd() with sns.plotting_context("paper"): self.g = sns.FacetGrid(self._table, col=self._col_factor, col_wrap=self._col_wrap, row=self._row_factor, sharex=True, sharey=True)
def _plot_mesh(self, mesh, options): 'Plot the mesh.' gdim = mesh.geometry().dim() if gdim < 2: raise ValueError('Invalid geometrical dimension. Must be > 1.') # Optionally turn on xkcd xkcd = options['xkcd'] if xkcd: plt.xkcd() fig = plt.figure() # Get axes based on 2d or 3d ax = fig.gca(projection='3d') if gdim > 2 else fig.gca() # Prepare axis labels for i in range(gdim): x = chr(ord('x') + i) label = x if xkcd else ('$%s$' % x) eval("ax.set_%slabel('%s')" % (x, label)) # Get colors for plotting edges cmap = plt.get_cmap(options['colors']['mesh']) edge_color = cmap(cmap.N/2) bdr_edge_color = cmap(9*cmap.N/10) # Plot the edges and get min/max of coordinate axis x_min_max = self._plot_edges(ax, mesh, edge_color, bdr_edge_color) # Fix the limits for figure for i in range(gdim): xi_min, xi_max = x_min_max[i] eval('ax.set_%slim(%g, %g)' % (chr(ord('x') + i), xi_min, xi_max)) return fig
def makePlot(filename, xkcd, data): import numpy as np import matplotlib import matplotlib.pyplot as plt data.sort(key=lambda x: x[1]) # sort the data, helps the pie labels = [m[0] for m in data] # extract the labels sizes = [m[1] for m in data] # extract the values # make better colors and cycle through them cmap = plt.cm.GnBu # http://matplotlib.org/examples/color/colormaps_reference.html colors = cmap(np.linspace(0., 0.75, len(sizes))) fig = plt.figure() if xkcd: plt.xkcd() # uncomment for xkcd style plots plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=0, # this helps with the labels of the small slices wedgeprops={'linewidth':'0'}, # makes the pie look nicer colors = colors, # use our pretty colors textprops={'fontsize':'x-small'}) # make the %s small to fit in pies # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') fig.savefig(filename, format="png")
def plot_time_series(data): buf = StringIO() plt.xkcd() plt.xlabel("Date") plt.ylabel("Number of events") axes = plt.axes() # loc = mdates.AutoDateLocator() # axes.xaxis.set_major_locator(loc) # axes.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) max_y = 0 for i, (name, series) in enumerate(data): series.sort() series = _group_by_date(series) # print name, series times, values = zip(*series) max_y = max(max_y, max(values)) # times = map(datetime.fromtimestamp, times) plt.plot(times, values, label=name, color=colors[i%len(colors)], markersize=10.0, marker=markers[i%len(markers)], ) # plt.plot_date(x=times, y=values, label=name, # color=colors[i%len(colors)], # markersize=10.0, # marker=markers[i%len(markers)], # ) plt.ylim(ymin=0, ymax=max_y+10) xlim = plt.xlim() plt.xlim(xlim[0]-3, xlim[1]+3) plt.legend() plt.savefig(buf, format='png') plt.close() return buf.getvalue()
def main(argv): filename = argv[1] f = open(filename, 'r') data = [] for line in f: d = [ float(e) for e in line.split('\t')] data.append(d) f.close() d = dict() for row in data: c = row[0] gamma = row[1] if c not in d: d[c] = dict() d[c][gamma] = row[2] # set up styles styles = ['r', 'g', 'b', 'k', 'y', 'm', 'c'] styles = [ s + ":" for s in styles ] + [s + "--" for s in styles] #+ [s + "-." for s in styles] random.shuffle(styles) styles = styles*3 plt.xkcd() for (c, style) in zip(d, styles): gs = sorted([k for k in d[c]]) y = [d[c][v] for v in gs] x = [log(x) for x in gs] plt.plot(x, y, style+"o", label=str(c)) plt.legend() plt.xticks(x, gs, rotation='vertical') plt.show()
def run_plot(num_pts=100, maximize=False, interval_secs=5, xaxis_fmt='%I:%M'): """Runs the interactive plot of potato load""" matplotlib.rcParams['toolbar'] = 'None' if maximize: mng = plt.get_current_fig_manager() mng.resize(*mng.window.maxsize()) plt.gcf().canvas.set_window_title(' ') plt.xkcd() plt.ion() plt.show() data = [collections.deque([load], num_pts) for load in get_loads()] times = collections.deque([datetime.datetime.now()], num_pts) seaborn.set_palette('Set2', len(data)) while True: for loads, new_load in zip(data, get_loads()): loads.append(new_load) times.append(datetime.datetime.now()) plt.clf() for loads in data: plt.plot(times, loads) plt.title('AML Lab Cluster Loads', fontsize=60) plt.gca().xaxis.set_major_formatter(dates.DateFormatter(xaxis_fmt)) plt.draw() time.sleep(interval_secs)
def plot(title, data, savename): plt.title(title) plt.figure(figsize=(10, 8)) plt.subplot(111) plt.xkcd() plt.plot(data_to_plot) plt.xticks(range(24)) plt.savefig(savename)
def plot_histogram(sequence, k, filename, title=None): plot.xkcd() plot.grid(True, linewidth=0.5, zorder=0) n, bins, patches = plot.hist(sequence, k, zorder=3) plot.ylim(0, max(n) * 1.25) plot.title(title if title else '') plot.savefig('../graphics/' + filename + '.png') plot.clf()
def plot_two_histograms(sequence1, sequence2, k, label1, label2, filename, title=None, range_p=None): plot.xkcd() plot.hist(sequence1, k, label=label1, range=range_p, normed=True, color='blue', alpha=0.5) plot.hist(sequence2, k, label=label2, range=range_p, normed=True, color='green', alpha=0.5) plot.title(title if title else '') plot.legend(loc='upper right') plot.savefig('../graphics/' + filename + '.png') plot.clf()
def plot_bias(clf_list = ['test_small','rt_small','test2_small'],return_df = False,XKCD = False): """plots some differences between two output files. right now plots for every class and every classifier mean max std diff(clfx-clfy) plt.xkcd() is optional. """ if XKCD == True: plt.xkcd() print('damn') df = load_all_dfs(clf_list) df = df.swaplevel(0,1) del df['std'] df.hist() plt.figure() for clf in clf_list: df.ix[clf].mean().plot(label = clf,figsize=(16, 4)) plt.legend(loc='upper right') plt.title('mean') plt.figure() # c = df.columns for clf in clf_list: #df[c[1:]].ix[clf].max().plot(label = clf,figsize=(16, 4)) df.ix[clf].max().plot(label = clf,figsize=(16, 4)) plt.legend(loc='upper right') plt.title('max') plt.figure() for clf in clf_list: df.ix[clf].std().plot(label = clf,figsize=(16, 4)) plt.legend(loc='upper right') plt.title('std') plt.figure() used_list = [] for clf in clf_list: for clf2 in clf_list: if (clf != clf2) and ({clf,clf2} not in used_list): diff = ((df.ix[clf] - df.ix[clf2])**2)**(1/2) diff.mean().plot(label = clf+' - ' +clf2,figsize=(16, 4)) used_list.append({clf,clf2}) plt.legend(loc='upper right') plt.title('difference') print('damnover') if return_df == True: return df
def time_amplitude_plot(time, data, save_to): plt.close() plt.xkcd() plt.plot(time, data, color='#FF69B4') plt.title('Time-Amplitude plot', color='#4B0082') plt.xlabel('time', color='#4B0082') plt.ylabel('amplitude', color='#4B0082') plt.savefig(save_to)
def plot(x,y,fn="graph.png",start=None): actions = y.keys() sactions = order[:] if set(actions) == set(sactions): actions = sactions[:] #actions.sort() x = [datetime.fromtimestamp(xv) for xv in x] if xkcd: plt.xkcd() fig, ax = plt.subplots() cc =ax._get_lines.color_cycle for a in actions: al=a ac=next(cc) if namemap.has_key(a): al=namemap[a] if linemap.has_key(a): ac=linemap[a] ax.plot_date(x,[ys/3600.0 for ys in y[a]],'-',color=ac,label=al,linewidth=2) if start is not None: ax.set_xlim([datetime.fromtimestamp(start),datetime.now()]) window = ax.get_xlim() if (window[1]-window[0]) < 5: ax.xaxis.set_major_locator(md.HourLocator(byhour=(0,12))) ax.xaxis.set_major_formatter(md.DateFormatter('%d.%m.')) ax.xaxis.set_minor_locator(md.HourLocator()) ax.xaxis.set_minor_formatter(md.DateFormatter('%H')) if xkcd: ax.xaxis.set_tick_params(which="major",pad=25) else: ax.xaxis.set_tick_params(which="major",pad=15) fig.canvas.draw() for label in ax.xaxis.get_minorticklabels(): if label.get_text() not in ('00','06','12','18'): label.set_visible(False) else: ax.xaxis.set_major_locator(md.DayLocator()) ax.xaxis.set_major_formatter(md.DateFormatter('%d.%m.')) #ax.xaxis.set_minor_locator(md.HourLocator()) #ax.xaxis.set_minor_formatter(md.DateFormatter('')) ax.yaxis.set_major_locator(tic.MultipleLocator(12)) ax.yaxis.set_minor_locator(tic.MultipleLocator(1)) ax.yaxis.grid(True, which="both",linewidth=1) ax.set_title('Baby Tracker') ax.set_ylabel('verstrichende Zeit [h]') ax.autoscale_view() ax.grid(True, linewidth=1) if xkcd: ax.tick_params(width=2,length=6,which='minor') fig.autofmt_xdate(rotation="0", ha="center") ax.legend(loc='best') fig.savefig(fn,dpi=144)
def plot_pair(x, y1, y2, filename, ylim, title=None, color1='skyblue', color2='darkorange', label1='y1', label2='y2'): plot.xkcd() plot.plot(x, y1, color=color1, label=label1) plot.plot(x, y2, color=color2, label=label2) plot.ylim(-ylim, ylim) plot.title(title) plot.legend() plot.savefig('graphics/{}.png'.format(filename)) plot.clf()
def draw_graph(g, parameter, size_of_nodes, number): """ draws plot according to parameter of interest and size of nodes """ node_labels = find_top_nodes(g, parameter, number) plt.xkcd() plt.figure(1, figsize=(30, 25)) coord = nx.spring_layout(g) nx.draw(g, pos=coord, nodelist=parameter.keys(), node_size=[d*size_of_nodes for d in parameter.values()], node_color=list(parameter.values()), font_size=25, cmap=plt.cm.get_cmap('RdBu_r'), labels=node_labels)
def draw_bar_plot(values, max_to_plot=50, save_file=None, x_label='X axis', y_label='Y axis', x_dim=10, y_dim=10, sorted=True, xkcd=True): """ Plots a bar graph given a dictionary of key-value pairs. Parameters ---------- values : dict dict of the form x -> y max_to_plot : int the maximum values to plot on the bar plot, defaults to 50 save_file : str, optional the name of the file where you want to store the bar plot. Must have extension .png If not specified, no file will be saved. If not the absoulte path, will be saved relative to current working directory. x_label : str, optional label for the x-axis y_label : str, optional label for the y axis x_dim : int, optional width of the bounding box, defaults to 10 units y_dim : int, optional height of the bounding box, defaults to 10 units sorted : bool, optional sort the columns in increasing order of counts. defaults to True xkcd : bool, optional plot the graph in xkcd style. defaults to true Returns ------- None Examples -------- >>> values = {'a' : 10, 'b' : 5, 'c' : 12} >>> draw_bar_plot(values, save_file='example.png') """ if xkcd: plt.xkcd() count_series = pandas.Series(values) if sorted: count_series.sort(axis=1) if count_series.size > max_to_plot: count_series = count_series[: max_to_plot] count_series.plot(kind='bar', figsize=(x_dim, y_dim), ascending=False) plt.ylabel(y_label) plt.xlabel(x_label) if save_file: plt.savefig(save_file) plt.show()
def cdf_prep(node, _): """Write a graph of the cdf of @p node to the current pyplot.""" # pylint: disable = invalid-name plt.xkcd() cost = node.final_cost() (x_min, x_max) = bounds_for_plotting(cost) xs = linspace(x_min, x_max, NUM_SAMPLES, endpoint=True) ys = [cost.cdf(x) for x in xs] cubic_y = interp1d(xs, ys, kind="cubic") xs_dense = linspace(x_min, x_max, GRAPH_RESOLUTION, endpoint=True) plt.plot(xs_dense, cubic_y(xs_dense), '-')
def covid_plots(country, countries4Plot,\ startdate="2/20/20",predict_range = 60, \ startCase = 180, opt = 5, version = "1", \ show = False, maxDate="08/31/20",model=""): #choose country countrySEAIRD = country #initial vars a = 0.0 b = 0.0 c = 0.0 date = [] #load CSV file dateparse = lambda x: pd.datetime.strptime(x, '%m/%d/%Y') df=pd.read_csv('data/time_series_19-covid-Confirmed-country.csv', \ delimiter=',',parse_dates=True, date_parser=dateparse,header=None) df = df.transpose() #prepare data for plotting country1 = countries4Plot[0] [time1, cases1] = getCases(df, country1) country2 = countries4Plot[1] [time2, cases2] = getCases(df, country2) country3 = countries4Plot[2] [time3, cases3] = getCases(df, country3) country4 = countries4Plot[3] [time4, cases4] = getCases(df, country4) country5 = countries4Plot[4] [time5, cases5] = getCases(df, country5) country10 = country [time10, cases10] = getCases(df, country10) if opt == 1 or opt == 0 or opt == 4: model = 'SEAIRD' df = loadDataFrame('./data/SEAIRDv5_Yabox_' + country + '.pkl') time6, cases6 = predictionsPlot(df, startCase + 200) # #model # growth = 1.0125/2 # x,y = logGrowth(growth,200) # growth1 = 1.025/2 # x1,y1 = logGrowth(growth1,200) # Plot the data #ax.figure(figsize=(19.20,10.80)) color_bg = '#FEF1E5' # lighter_highlight = '#FAE6E1' darker_highlight = '#FBEADC' plt.rcParams['figure.figsize'] = [12, 9] plt.rc('font', size=14) with plt.xkcd(): fig, ax = plt.subplots(facecolor=color_bg) ax.patch.set_facecolor(darker_highlight) # Hide the right and top spines ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #fonts for the thicks for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontproperties(comic_font) label.set_fontsize(16) # Size here overrides font_prop plt.plot(time2, cases2, 'r-', label=strip_accents(country2), markevery=3) plt.plot(time4, cases4, 'm-', label=strip_accents(country4), markevery=3) plt.plot(time5, cases5, 'c-', label=strip_accents(country5), markevery=3) plt.plot(time3, cases3, 'g-', label=strip_accents(country3), markevery=3) plt.plot(time6, cases6, '--', c='0.6', label=strip_accents(country) + " " + model) plt.plot(time1, cases1, 'b-', label=strip_accents(country1)) # plt.plot(x, y,'y--',label='{:.1f}'.format((growth-1)*100)+'% per day',alpha=1) # plt.plot(x1, y1,'y-.',label='{:.1f}'.format((growth1-1)*100)+'% per day',alpha=1) plt.rc('font', size=11) plt.annotate( strip_accents(country3) + " {:.1f} K".format( cases3[len(cases3) - 1] / 1000), # this is the text (time3[len(cases3) - 1], cases3[len(cases3) - 1]), # this is the point to label textcoords="offset points", # how to position the text xytext=(100, -20), # distance from text to points (x,y) ha='right', fontproperties=comic_font, fontsize=16 ) # horizontal alignment can be left, right or center # idx=int(np.argmax(cases6)) # plt.annotate("Peak {:.1f} K".format(max(cases6)/1000), # this is the text # (time6[idx],cases6[idx]), # this is the point to label # textcoords="offset points", # how to position the text # xytext=(20,5), # distance from text to points (x,y) # ha='right',fontproperties=comic_font,fontsize=16) # horizontal alignment can be left, right or center plt.annotate( strip_accents(country1) + " {:.1f} K".format( cases1[len(cases1) - 1] / 1000), # this is the text (time1[len(cases1) - 1], cases1[len(cases1) - 1]), # this is the point to label textcoords="offset points", # how to position the text xytext=(70, -20), # distance from text to points (x,y) ha='center', fontproperties=comic_font, fontsize=16 ) # horizontal alignment can be left, right or center plt.annotate('Modeling Team for Sao Paulo State IPT, USP, ATS', fontproperties=subtitle_font, fontsize=16, xy=(1.06, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', rotation=90) plt.annotate('Source: https://data.brasil.io', fontproperties=subtitle_font, fontsize=16, xy=(1.06, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='left', rotation=90) plt.xlabel('Days after 100th case', fontproperties=comic_font) plt.ylabel('Official registered cases', fontproperties=comic_font) plt.yscale('log') # Hide grid lines # ax.grid(False) # Adding a title and a subtitle plt.text(x=0.02, y=1.1, s="Corona virus growth", fontsize=34, weight='bold', alpha=.75, transform=ax.transAxes, fontproperties=heading_font) plt.text(x=0.02, y=1.05, s="Comparison selected countrys and model for " + country, fontsize=26, alpha=.85, transform=ax.transAxes, fontproperties=subtitle_font) leg = ax.legend(frameon=False, prop=comic_font, fontsize=12, loc='lower right') for lh in leg.legendHandles: lh.set_alpha(0.75) ax.grid(True, linestyle='--', linewidth='2', color='white', alpha=0.2) fig.tight_layout() #save figs strFile = './results/coronaPythonEN_' + version + '.png' fig.savefig(strFile, facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor()) # Show the plot plt.show() plt.close() # Show the plot if show: plt.show() plt.close() if opt == 2 or opt == 0: if opt == 2: #model #33% per day x = [] y = [] x = np.linspace(0, 30, 31) for i in range(0, len(x)): if i == 0: y.append(100) else: y.append(y[i - 1] * 1.33) #50% per day x1 = [] y1 = [] x1 = np.linspace(0, 30, 31) for i in range(0, len(x1)): if i == 0: y1.append(100) else: y1.append(y1[i - 1] * 1.25) #model fitting casesFit = cases10 timeFit = time10 maxCases = 12e6 maxTime = 300 guessExp = 0.01 #logistic curve fit = curve_fit(logistic_model, timeFit, casesFit, p0=[20, 100, maxCases]) print("Infection speed=", fit[0][0]) print("Day with the maximum infections occurred=", int(fit[0][1] + 0.5)) print( "Total number of recorded infected people at the infection’s end=", int(fit[0][2])) # #exponential curve # exp_fit = curve_fit(exponential_model,timeFit,casesFit,p0=[guessExp*2,guessExp/2,guessExp/4],maxfev=100000) # Plot the data #ax.figure(figsize=(19.20,10.80)) color_bg = '#FEF1E5' # lighter_highlight = '#FAE6E1' darker_highlight = '#FBEADC' plt.rcParams['figure.figsize'] = [12, 9] plt.rc('font', size=14) with plt.xkcd(): fig, ax = plt.subplots(facecolor=color_bg) ax.patch.set_facecolor(darker_highlight) # Hide the right and top spines ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #fonts for the thicks for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontproperties(comic_font) label.set_fontsize(16) # Size here overrides font_prop #plot pred_x = np.arange(len(timeFit), maxTime, 1) extendT = np.concatenate([timeFit, pred_x]) # Predicted logistic curve ax.plot(extendT, [ logistic_model(i, fit[0][0], fit[0][1], fit[0][2]) for i in extendT ], label="Logistic model") # # Predicted exponential curve # ax.plot(extendT, [exponential_model(i,exp_fit[0][0], # exp_fit[0][1],exp_fit[0][2]) for i in extendT], label="Exponential model" ) # Real data ax.scatter(timeFit, casesFit, label="Real cases " + strip_accents(country), color="red") #axis, limits and legend plt.xlabel("Days since 100th case", fontproperties=comic_font) plt.ylabel("Total number of infected people", fontproperties=comic_font) plt.ylim((0, int(1.05 * fit[0][2]))) leg = plt.legend(frameon=False) for lh in leg.legendHandles: lh.set_alpha(0.75) plt.annotate('Modeling Team for Sao Paulo State IPT, USP, ATS', fontproperties=subtitle_font, fontsize=16, xy=(1.06, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', rotation=90) plt.annotate('Source: https://data.brasil.io', fontproperties=subtitle_font, fontsize=16, xy=(1.06, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='left', rotation=90) plt.annotate('Total infected = {:.2f} M'.format(fit[0][2] / 1e6), fontsize=16, xy=(0.97, 0.60), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', fontproperties=comic_font) plt.annotate('Infection speed = {:.2f}'.format(fit[0][0]), fontsize=16, xy=(0.96, 0.55), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', fontproperties=comic_font) plt.annotate('Max Infection at {:.0f} day'.format(fit[0][1]), fontsize=16, xy=(fit[0][1], logistic_model(fit[0][1], fit[0][0], fit[0][1], fit[0][2])), xytext=(-35, 0), textcoords='offset points', arrowprops={'arrowstyle': '-|>'}, ha='right', fontproperties=comic_font) # Adding a title and a subtitle plt.text(x=0.02, y=1.1, s="Curve Fitting with Simple Math Function", fontsize=30, weight='bold', alpha=.75, transform=ax.transAxes, fontproperties=heading_font) plt.text(x=0.02, y=1.05, s="Logistic Function fitted with real data from " + country, fontsize=22, alpha=.85, transform=ax.transAxes, fontproperties=subtitle_font) leg = ax.legend(frameon=False, prop=comic_font, fontsize=26) for lh in leg.legendHandles: lh.set_alpha(0.75) ax.grid(True, linestyle='--', linewidth='2', color='white', alpha=0.2) fig.tight_layout() #save figs strFile = './results/coronaPythonModelEN' + country + '.png' fig.savefig(strFile, facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor()) if show: plt.show() plt.close() if opt == 3 or opt == 0 or opt == 4: plt.rcParams['figure.figsize'] = [12, 9] plt.rc('font', size=14) if country == country1: casesGrowth = cases1 timeGrowth = time1 maxCases = 27e4 maxTime = 80 guessExp = 2 if country == country2: casesGrowth = cases2 timeGrowth = time2 maxCases = 13e4 maxTime = 80 guessExp = 2 if country == country3: casesGrowth = cases3 timeGrowth = time3 maxCases = 30e3 maxTime = 50 guessExp = 0.5 if country == country4: casesGrowth = cases4 timeGrowth = time4 maxCases = 12e4 maxTime = 80 guessExp = 2 if country == country5: casesGrowth = cases5 timeGrowth = time5 maxCases = 12e4 maxTime = 80 guessExp = 2 #growth rate growth = [] for i in range(0, len(casesGrowth) - 1): growth.append(100 * float(casesGrowth[i + 1]) / float(casesGrowth[i]) - 100) #Setup dummy data N = 10 ind = timeGrowth[1:] bars = growth plt.rcParams['figure.figsize'] = [12, 9] plt.rc('font', size=14) #ax.figure(figsize=(19.20,10.80)) color_bg = '#FEF1E5' # lighter_highlight = '#FAE6E1' darker_highlight = '#FBEADC' colors = cm.rainbow( np.asfarray(growth, float) / float(max(np.asfarray(growth, float)))) with plt.xkcd(): fig, ax = plt.subplots(facecolor=color_bg) plot = ax.scatter(growth, growth, c=growth, cmap='rainbow') fig.colorbar(plot) ax.cla() # Plot the data ax.patch.set_facecolor(darker_highlight) # Hide the right and top spines ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #fonts for the thicks for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontproperties(comic_font) label.set_fontsize(16) # Size here overrides font_prop #Plot bars plt.bar(ind, bars, color=colors) plt.xlabel('Days since 100th case', fontproperties=comic_font) # Make the y-axis label and tick labels match the line color. plt.ylabel('Growth official cases per day [%]', fontproperties=comic_font) #Plot a line plt.axhline(y=10, color='r', linestyle='--') plt.annotate( "doubling each 10 days", # this is the text (75, 10), # this is the point to label textcoords="offset points", # how to position the text xytext=(10, 5), # distance from text to points (x,y) ha='right', weight='bold', fontsize=18, fontproperties=comic_font) # horizontal alignment can be left, right or center plt.annotate('Modeling Team for Sao Paulo State IPT, USP, ATS', fontproperties=subtitle_font, fontsize=16, xy=(1.24, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', rotation=90) plt.annotate('Source: https://data.brasil.io', fontproperties=subtitle_font, fontsize=16, xy=(1.24, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='left', rotation=90) # Hide grid lines ax.grid(True, linestyle='--', linewidth='2', color='white', alpha=0.2) # Adding a title and a subtitle plt.text(x=0.02, y=1.1, s="Relative Growth per Day", fontsize=34, weight='bold', alpha=.75, transform=ax.transAxes, fontproperties=heading_font) plt.text(x=0.02, y=1.05, s="Real Data for " + country, fontsize=26, alpha=.85, transform=ax.transAxes, fontproperties=subtitle_font) fig.tight_layout() #save figs strFile = './results/coronaPythonGrowthEN_' + country + '.png' fig.savefig(strFile, facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor()) if show: plt.show() plt.close() #growth rate growth = [] for i in range(0, len(casesGrowth) - 1): growth.append(float(casesGrowth[i + 1]) - float(casesGrowth[i])) #Setup dummy data N = 10 ind = timeGrowth[1:] # bars = growth bars = [x / 1000 for x in growth] growth = bars plt.rcParams['figure.figsize'] = [12, 9] plt.rc('font', size=14) #ax.figure(figsize=(19.20,10.80)) color_bg = '#FEF1E5' # lighter_highlight = '#FAE6E1' darker_highlight = '#FBEADC' colors = cm.rainbow( np.asfarray(growth, float) / float(max(np.asfarray(growth, float)))) with plt.xkcd(): fig, ax = plt.subplots(facecolor=color_bg) plot = ax.scatter(growth, growth, c=growth, cmap='rainbow') fig.colorbar(plot) ax.cla() ax.patch.set_facecolor(darker_highlight) # Hide the right and top spines ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #Plot bars plt.bar(ind, bars, color=colors) plt.xlabel('Days since 100th case', fontproperties=comic_font) # Make the y-axis label and tick labels match the line color. plt.ylabel('Growth official cases per day [*1000]', fontproperties=comic_font) plt.annotate('Modeling Team for Sao Paulo State IPT, USP, ATS', fontproperties=subtitle_font, fontsize=16, xy=(1.24, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', rotation=90) plt.annotate('Source: https://data.brasil.io', fontproperties=subtitle_font, fontsize=16, xy=(1.24, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='left', rotation=90) # Hide grid lines ax.grid(True, linestyle='--', linewidth='2', color='white', alpha=0.2) # Adding a title and a subtitle plt.text(x=0.02, y=1.1, s="Absolute Growth per Day", fontsize=34, weight='bold', alpha=.75, transform=ax.transAxes, fontproperties=heading_font) plt.text(x=0.02, y=1.05, s="Real Data for " + country, fontsize=26, alpha=.85, transform=ax.transAxes, fontproperties=subtitle_font) fig.tight_layout() #save figs strFile = './results/coronaPythonGrowthDeltaCasesEN_' + country + '.png' fig.savefig(strFile, facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor()) if show: plt.show() plt.close() if opt == 5 or opt == 0: df = loadDataFrame('./data/SEAIRDv5_Yabox_' + country + '.pkl') df.index = pd.to_datetime(df.index, format='%m/%d/%y') df = df[df.index <= datetime.strptime(maxDate, '%m/%d/%y')] color_bg = '#FEF1E5' # lighter_highlight = '#FAE6E1' darker_highlight = '#FBEADC' # plt.rc('font', size=14) with plt.xkcd(): fig, ax = plt.subplots(figsize=(15, 10), facecolor=color_bg) ax.patch.set_facecolor(darker_highlight) # Hide the right and top spines ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #fonts for the thicks for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontproperties(comic_font) label.set_fontsize(16) # Size here overrides font_prop # Adding a title and a subtitle plt.text(x=0.02, y=1.1, s="SEAIR-D Model for " + country, fontsize=30, weight='bold', alpha=.75, transform=ax.transAxes, fontproperties=heading_font) plt.text(x=0.02, y=1.05, s="Optimization fitted with coronavirus.jhu.edu data", fontsize=26, alpha=.85, transform=ax.transAxes, fontproperties=subtitle_font) #limits for plotting ax.set_ylim((0, max(df.iloc[:]['susceptible']) * 1.1)) ax.xaxis_date() ax.plot(df['susceptible'], 'g-', label="Susceptible") ax.plot(df['exposed'], 'r-', label="Exposed") ax.plot(df['asymptomatic'], 'b-', label="Asymptomatic") #plt.xticks(np.arange(0, predict_range, predict_range/8)) ax.plot(df['infected'], 'y-', label="Infected") ax.plot(df['predicted_recovered'], 'c-', label="Recovered") ax.plot(df['predicted_deaths'], 'm-', label="Deaths") ax.plot(df['infected_data'], 'o', label="Infected data") ax.plot(df['death_data'], 'x', label="Death data") ax.plot(df['recovered'], '+', label="Recovered data") #format legend leg = ax.legend(frameon=False, prop=comic_font, fontsize=20) for lh in leg.legendHandles: lh.set_alpha(0.75) ax.grid(True, linestyle='--', linewidth='2', color='white', alpha=0.4) #plot margin annotation plt.annotate('Modeling Team for Sao Paulo State IPT, USP, ATS', xy=(1.04, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', rotation=90, fontproperties=subtitle_font, fontsize=16) plt.annotate( 'Original SEAIR-D with delay model, São Paulo, Brazil', xy=(1.045, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='left', rotation=90, fontproperties=subtitle_font, fontsize=16) #labels for x and y axis # plt.xlabel("Date", fontproperties=comic_font) # plt.ylabel("Number of People", fontproperties=comic_font) #plot layout fig.tight_layout() #file name to be saved strFile = "./results/modelSEAIRDOpt" + country + version + model + ".png" #remove previous file if os.path.isfile(strFile): os.remove(strFile) # Opt.: os.system("del "+strFile) #figure save and close fig.savefig(strFile, facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor()) if show: plt.show() plt.close() #format background with plt.xkcd(): fig, ax = plt.subplots(figsize=(15, 10), facecolor=color_bg) ax.patch.set_facecolor(darker_highlight) # Hide the right and top spines ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #fonts for the thicks for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontproperties(comic_font) label.set_fontsize(16) # Size here overrides font_prop ax.set_ylim(0, max(df['infected_data'] * 1.1)) # Adding a title and a subtitle plt.text(x=0.02, y=1.1, s="Zoom SEAIR-D Model for " + country, fontsize=30, weight='bold', alpha=.75, transform=ax.transAxes, fontproperties=heading_font) plt.text(x=0.02, y=1.05, s="Optimization fitted with coronavirus.jhu.edu data", fontsize=26, alpha=.85, transform=ax.transAxes, fontproperties=subtitle_font) ax.xaxis_date() #plt.xticks(np.arange(0, predict_range, predict_range/8)) ax.plot(df['infected'], 'y-', label="Infected") ax.plot(df['predicted_recovered'], 'c-', label="Recovered") ax.plot(df['predicted_deaths'], 'm-', label="Deaths") ax.plot(df['infected_data'], 'o', label="Infected data") ax.plot(df['death_data'], 'x', label="Death data") ax.plot(df['recovered'], '+', label="Recovered data") #format legend leg = ax.legend(frameon=False, prop=comic_font, fontsize=20) for lh in leg.legendHandles: lh.set_alpha(0.75) ax.grid(True, linestyle='--', linewidth='2', color='white', alpha=0.2) plt.annotate('Modeling Team for Sao Paulo State IPT, USP, ATS', xy=(1.04, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', rotation=90, fontproperties=subtitle_font, fontsize=16) plt.annotate( 'Original SEAIR-D with delay model, São Paulo, Brazil', xy=(1.045, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='left', rotation=90, fontproperties=subtitle_font, fontsize=16) #labels for x and y axis # plt.xlabel("Date", fontproperties=comic_font) # plt.ylabel("Number of People", fontproperties=comic_font) #plot layout fig.tight_layout() #file name to be saved strFile = "./results/ZoomModelSEAIRDOpt" + country + version + model + ".png" #remove previous file if os.path.isfile(strFile): os.remove(strFile) # Opt.: os.system("del "+strFile) #figure save and close fig.savefig(strFile, facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor()) if show: plt.show() plt.close() with plt.xkcd(): fig, ax = plt.subplots(figsize=(15, 10), facecolor=color_bg) ax.patch.set_facecolor(darker_highlight) # Hide the right and top spines ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #fonts for the thicks for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontproperties(comic_font) label.set_fontsize(16) # Size here overrides font_prop # Adding a title and a subtitle plt.text(x=0.02, y=1.1, s="Cases per day for " + country, fontsize=30, weight='bold', alpha=.75, transform=ax.transAxes, fontproperties=heading_font) plt.text(x=0.02, y=1.05, s="Optimization fitted with coronavirus.jhu.edu data", fontsize=26, alpha=.85, transform=ax.transAxes, fontproperties=subtitle_font) ax.xaxis_date() lst = (np.diff(df['infected'])) l = df['infected_data'].last_valid_index() lst2 = (np.diff(df['infected_data'][:l])) df2 = pd.DataFrame(data=lst, index=df.index[:len(lst)], columns=['infectedDay']) df3 = pd.DataFrame(data=lst2, index=df.index[:len(lst2)], columns=['infectedDay']) df2 = df2[df2.infectedDay < (df2.infectedDay.mean() + 2 * df2.infectedDay.std())] df3 = df3[df3.infectedDay < (df3.infectedDay.mean() + 2 * df3.infectedDay.std())] df2 = df2[df2.infectedDay > (df2.infectedDay.mean() - 2 * df2.infectedDay.std())] df3 = df3[df3.infectedDay > (df3.infectedDay.mean() - 2 * df3.infectedDay.std())] df3.rolling(7).mean()['infectedDay'].plot(label="7-day real", style='o') df2.rolling(7).mean()['infectedDay'].plot(label="7-day model") #format legend leg = ax.legend(frameon=False, prop=comic_font, fontsize=20) for lh in leg.legendHandles: lh.set_alpha(0.75) ax.grid(True, linestyle='--', linewidth='2', color='white', alpha=0.2) plt.annotate('Modeling Team for Sao Paulo State IPT, USP, ATS', xy=(1.04, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', rotation=90, fontproperties=subtitle_font, fontsize=16) plt.annotate( 'Original SEAIR-D with delay model, São Paulo, Brazil', xy=(1.045, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='left', rotation=90, fontproperties=subtitle_font, fontsize=16) #labels for x and y axis plt.xlabel("Date", fontproperties=comic_font) plt.ylabel("Cases per day", fontproperties=comic_font) #plot layout fig.tight_layout() #file name to be saved strFile = "./results/dailyCasesSEAIRDOpt" + country + version + model + ".png" #remove previous file if os.path.isfile(strFile): os.remove(strFile) # Opt.: os.system("del "+strFile) #figure save and close fig.savefig(strFile, facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor()) if show: plt.show() plt.close() with plt.xkcd(): fig, ax = plt.subplots(figsize=(15, 10), facecolor=color_bg) ax.patch.set_facecolor(darker_highlight) # Hide the right and top spines ax.spines['left'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) #fonts for the thicks for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontproperties(comic_font) label.set_fontsize(16) # Size here overrides font_prop # Adding a title and a subtitle plt.text(x=0.02, y=1.1, s="Deaths per day for " + country, fontsize=30, weight='bold', alpha=.75, transform=ax.transAxes, fontproperties=heading_font) plt.text(x=0.02, y=1.05, s="Optimization fitted with coronavirus.jhu.edu data", fontsize=26, alpha=.85, transform=ax.transAxes, fontproperties=subtitle_font) ax.xaxis_date() lst = (np.diff(df['predicted_deaths'])) l = df['death_data'].last_valid_index() lst2 = (np.diff(df['death_data'][:l])) df2 = pd.DataFrame(data=lst, index=df.index[:len(lst)], columns=['deathDay']) df3 = pd.DataFrame(data=lst2, index=df.index[:len(lst2)], columns=['deathDay']) df2 = df2[df2.deathDay < (df2.deathDay.mean() + 2 * df2.deathDay.std())] df3 = df3[df3.deathDay < (df3.deathDay.mean() + 2 * df3.deathDay.std())] df2 = df2[df2.deathDay > (df2.deathDay.mean() - 2 * df2.deathDay.std())] df3 = df3[df3.deathDay > (df3.deathDay.mean() - 2 * df3.deathDay.std())] df3.rolling(7).mean()['deathDay'].plot(label="7-day real", style='o') df2.rolling(7).mean()['deathDay'].plot(label="7-day model") #format legend leg = ax.legend(frameon=False, prop=comic_font, fontsize=20) for lh in leg.legendHandles: lh.set_alpha(0.75) ax.grid(True, linestyle='--', linewidth='2', color='white', alpha=0.2) plt.annotate('Modeling Team for Sao Paulo State IPT, USP, ATS', xy=(1.04, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='right', rotation=90, fontproperties=subtitle_font, fontsize=16) plt.annotate( 'Original SEAIR-D with delay model, São Paulo, Brazil', xy=(1.045, 0.1), xycoords='axes fraction', xytext=(0, 0), textcoords='offset points', ha='left', rotation=90, fontproperties=subtitle_font, fontsize=16) #labels for x and y axis plt.xlabel("Date", fontproperties=comic_font) plt.ylabel("Deaths per day", fontproperties=comic_font) #plot layout fig.tight_layout() #file name to be saved strFile = "./results/dailyCasesSEAIRDOpt" + country + version + model + ".png" #remove previous file if os.path.isfile(strFile): os.remove(strFile) # Opt.: os.system("del "+strFile) #figure save and close fig.savefig(strFile, facecolor=fig.get_facecolor(), edgecolor=fig.get_edgecolor()) if show: plt.show() plt.close()
### BONUS: XCKD-STYLE PLOTS # CONGRATULATIONS! You made it to the very end of this debaucherous tutorial, # so you now get to see what is probably the most fantastic functionality in # matplotlib: plotting in the style of the xkcd webcomic! # Days spent programming t = np.arange(0, 600) # Average quality of code produced q = np.zeros_like(t) q[0:100] = t[0:100] * 2 # When you're a total n00b. q[100:200] = q[99] + np.arange( 100)**2.0 # When everything is suddenly amazing. q[200:600] = np.random.randint(0, q[199] * 2.0, 80).repeat( 5) # Aaaaand... when you've gone insane. # Plotting in xkcd-style plt.xkcd(scale=0.5, length=100, randomness=1) plt.plot(t, q) plt.xlabel("Days Spent Programming") plt.ylabel("Average Quality of Code Produced") plt.tick_params(axis='both', which='both', bottom='off', top='off', left='off', right='off') plt.show()
while 42: result, reason = rfidler.connect(port) if result: result, data = rfidler.command('PING') if result: break rfidler.disconnect() if os.path.exists('/dev/RFIDlerBL'): break current -= 1 continue current += 1 continue if command == 'XKCD': pyplot.xkcd() continue if command in ['PLOT', 'PLOTN', 'STORE', 'STOREN', 'LOAD']: if command in ['PLOT', 'STORE']: result, data = rfidler.command('ANALOGUE %s' % sys.argv[current]) elif command in ['PLOTN', 'STOREN']: result, data = rfidler.command('ANALOGUEN %s' % sys.argv[current]) else: result, data = load_data(sys.argv[current]) current += 1 if result: if command in ['PLOT', 'PLOTN', 'LOAD']: plot_data(data) else:
def CreateGanttChart(fname): """ Create gantt charts with matplotlib Give file name. """ if _blnXKCD: plt.xkcd() ylabels = [] customDates = [] try: textlist = open(fname).readlines() except: return # for tx in textlist: if not tx.startswith('#'): ylabel, startdate, enddate = tx.split(',') ylabels.append(ylabel.replace('\n', '')) customDates.append([ _create_date(startdate.replace('\n', '')), _create_date(enddate.replace('\n', '')) ]) ilen = len(ylabels) pos = np.arange(0.5, ilen * 0.5 + 0.5, 0.5) task_dates = {} for i, task in enumerate(ylabels): task_dates[task] = customDates[i] fig = plt.figure(figsize=(20, 8)) ax = fig.add_subplot(111) for i in range(len(ylabels)): start_date, end_date = task_dates[ylabels[i]] ax.barh((i * 0.5) + 0.5, end_date - start_date, left=start_date, height=0.3, align='center', edgecolor='lightgreen', color='orange', alpha=0.8) locsy, labelsy = plt.yticks(pos, ylabels) plt.setp(labelsy, fontsize=14) # ax.axis('tight') ax.set_ylim(bottom=-0.1, top=ilen * 0.5 + 0.5) #changed to 'top' from 'ymax' SM 2018-10-15 ax.grid(color='g', linestyle=':') ax.xaxis_date() rule = rrulewrapper(WEEKLY, interval=1) loc = RRuleLocator(rule) #formatter = DateFormatter("%d-%b '%y") formatter = DateFormatter("%d-%b") ax.xaxis.set_major_locator(loc) ax.xaxis.set_major_formatter(formatter) labelsx = ax.get_xticklabels() plt.setp(labelsx, rotation=30, fontsize=10) font = font_manager.FontProperties(size='small') ax.legend(loc=1, prop=font) ax.invert_yaxis() fig.autofmt_xdate() plt.savefig('Gantt\\' + _timestamp() + '.png') plt.show()
def draw_mooc_logo(): # the magical trick to get friendly pictures # that remind of the xkcd style with plt.xkcd(): # create figure my_dpi = 80 fig = plt.figure(dpi=my_dpi, figsize=(9, 6)) # we need more space for the labels and all fig.subplots_adjust(left=0.25, bottom=0.22, top=0.65) # do not use title, we draw our own texts fig.text(0.01, 0.01, "adaptation libre de http://xkcd.com/519/", fontsize=14, ha='left', va='bottom') # another text fig.text(0.5, 0.82, """Python 3 : des fondamentaux aux concept avances""", fontsize=45, ha='center', va='center') # a subplot ax = fig.add_subplot(1, 1, 1) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') # set scales ax.set_xlim([-0.5, 2.5]) ax.set_ylim([0, 110]) # set values ax.bar([i - 0.125 for i in range(3)], [5, 3, 100], 0.25) # draw labels for x and y ax.xaxis.set_ticks_position('bottom') ax.tick_params(size=0) ax.set_xticks([0, 1, 2]) ax.set_xticklabels([ "900\nHEURES\nDE COURS", "400\nHEURES\nDE DM", "UN MOOC\nA JOUER\nAVEC PYTHON" ]) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(26) plt.yticks([]) ax.set_ylabel("""utilite pour une carriere reussie""", rotation='horizontal', labelpad=80, va='center', fontsize=26) plt.savefig("xkcd.png", format="png") # show it plt.show()
def customise(self): """Force on xkcd style.""" plt.xkcd()
from matplotlib import pyplot as plt import json plt.xkcd() def read(): with open("scores.json", "r") as f: return json.load(f) print(read()) x = [list(read().keys()), list(read().values())] # print(x) plt.bar(x[0], x[1]) plt.xlabel("MENSCHEN") plt.ylabel("KNIEBEUGEN") plt.show()
def showLosses(losses_in_epochs): plt.xkcd() plt.xlabel('Rodada #') plt.ylabel('Perda') plt.plot(losses_in_epochs) plt.show()
def draw_diagram(budgets): """Draws a quick diagram to illustrate the overspend budgets.""" import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Rectangle # Define some parameters. The Slack image previews are ~360x150px, so # we need fonts and sizes that fit that well. matplotlib.rcParams.update({ "font.family": "Arial", "font.size": 20, "figure.figsize": (11, 4.6) }) # BECAUSE I CAN, DAMNIT. with plt.xkcd(): fig, axes = plt.subplots() # First we draw a box plot. We don't actually use any of the graph # elements it creates, but it sets up some axes, labels and tick marks # so we don't have to do that manually. # # Based on # https://matplotlib.org/examples/pylab_examples/boxplot_demo.html data = [[ b.budget_limit.amount, b.current_spend.amount, b.forecasted_spend.amount ] for b in budgets] labels = [b.name for b in budgets] axes.boxplot( data, labels=labels, vert=False, # This parameter ensures that the boxplot elements are drawn on # a low layer in the image. zorder=0.0, ) for i, budget in enumerate(budgets, start=1): # Now we immediately discard most of what we've just drawn! # We draw over it with a white box at a higher z-layer, so we can # draw lines ourselves. min_value = min([ budget.budget_limit.amount, budget.current_spend.amount, budget.forecasted_spend.amount, ]) max_value = max([ budget.budget_limit.amount, budget.current_spend.amount, budget.forecasted_spend.amount, ]) axes.add_patch( Rectangle( xy=(min_value - 10, i - 0.25), width=(max_value - min_value + 10), height=0.5, fill=True, color="white", zorder=1.0, )) # Then we draw our own lines to show the different parts of # this budget. line_limit = Line2D( xdata=[budget.budget_limit.amount, budget.budget_limit.amount], ydata=[i - 0.2, i + 0.2], color="green", linewidth=6, linestyle=":", ) axes.add_line(line_limit) line_forecast = Line2D( xdata=[ budget.forecasted_spend.amount, budget.forecasted_spend.amount ], ydata=[i - 0.2, i + 0.2], color="red", linewidth=6, linestyle=":", ) axes.add_line(line_forecast) line_current = Line2D( xdata=[ budget.current_spend.amount, budget.current_spend.amount ], ydata=[i - 0.25, i + 0.25], color="black", linewidth=10, ) axes.add_line(line_current) # Finally, we add these three lines to the legend. There's probably a # neater way of doing these with line styles, but I don't care enough to # learn how to do it "properly". legend_limit = Line2D(xdata=[], ydata=[], color="green", label="budget limit") legend_forecast = Line2D(xdata=[], ydata=[], color="red", label="forecast") legend_current = Line2D(xdata=[], ydata=[], color="black", label="current spend") plt.legend(handles=[legend_limit, legend_forecast, legend_current]) plt.savefig("figure.png", bbox_inches="tight") return "figure.png"
def main(): sns.set_style("ticks") #matplotlib.rcParams['font.sans-serif'] = "Comic Sans MS" # for the radial ticks thatn I didnt manage to change otherwise print('Reading race data...') data = pd.read_csv('https://docs.google.com/spreadsheets/d/16S4WFeQv5_mVwf5IkeHNBLFwDj3kpTra4C8fNkLJJLQ/export?gid=0&format=csv', dtype='float') print(' DONE\n') data = data.sort_values(by=['TWA']) # print(data) TWA = data['TWA'].values TWA_resampled = np.arange(0, 180.1, .1) # calculate polynomial if False: polar_fit = np.polyfit(data['TWA'], data['normalised_SPD_8nm'], 3) f = np.poly1d(polar_fit) SPD_fitted = f(TWA_resampled) else: f = interpolate.splrep(data['TWA'], data['normalised_SPD_8nm'], k=3, s=1) SPD_fitted = interpolate.splev(TWA_resampled, f) plt.figure() fig_grid = plt.GridSpec(2, 2) # --- FITTED MODEL --- with plt.xkcd(): ax = plt.subplot(fig_grid[0, 1]) ax.plot( TWA, data['normalised_SPD_8nm'].values, marker='o', color='gray', alpha=0.2, linestyle = 'None' ) ax.plot( TWA_resampled, SPD_fitted, marker='None', linestyle = '-', color='darkorange', label='Sailing speed' ) with plt.xkcd(): ax.xaxis.grid(linewidth=1.0) ax.yaxis.grid(linewidth=1.0) ax.set_xticks(np.arange(0,200,20)) plt.legend(loc='lower right') plt.ylabel('Sailing speed (nm)') sns.despine(bottom=True) # --- UPWIND SPEED --- upwind_SPD = SPD_fitted * np.cos(np.radians(TWA_resampled)) max_id = np.argmax(upwind_SPD) min_id = np.argmin(upwind_SPD) with plt.xkcd(): ax = plt.subplot(fig_grid[1, 1]) ax.plot( TWA_resampled, upwind_SPD, marker='None', linestyle = '-', color='darkred', label='Upwind speed' ) with plt.xkcd(): ax.plot( TWA_resampled[max_id], upwind_SPD[max_id], marker='o', color='black', alpha=1, linestyle = 'None', label='Optimal sailing points') ax.plot( TWA_resampled[min_id], upwind_SPD[min_id], marker='o', color='black', alpha=1, linestyle = 'None') plt.annotate( 'Max Upwind Speed ({:.2f}kn) at {:.1f} TWD'.format( upwind_SPD[max_id], TWA_resampled[max_id] ), xy=(TWA_resampled[max_id], upwind_SPD[max_id]), arrowprops=dict(arrowstyle='->'), xytext=(0, 2.2)) plt.annotate( 'Max Downwind Speed ({:.2f}kn) at {:.1f} TWD'.format( -upwind_SPD[min_id], TWA_resampled[min_id] ), xy=(TWA_resampled[min_id], upwind_SPD[min_id]), arrowprops=dict(arrowstyle='->'), xytext=(90, -2.8)) ax.xaxis.grid(linewidth=1.0) ax.yaxis.grid(linewidth=1.0) ax.set_xticks(np.arange(0,200,20)) plt.ylabel('Upwind speed (nm)') plt.xlabel('Wind direction (TWA)') plt.legend(loc='lower left') sns.despine() # FITTED MODEL POLAR with plt.xkcd(): ax = plt.subplot(fig_grid[:, 0], projection='polar') ax.plot( np.radians(TWA), data['normalised_SPD_8nm'].values, marker='o', color='gray', alpha=0.2, linestyle = 'None', label='Measurements' ) ax.plot( np.radians(TWA_resampled), SPD_fitted, marker='None', linestyle = '-', color='darkorange', label='Sailing speed' ) with plt.xkcd(): ax.plot( np.radians(TWA_resampled[max_id]), SPD_fitted[max_id], marker='o', color='black', alpha=1, linestyle = 'None', label='Optimal sailing points') ax.plot( np.radians(TWA_resampled[min_id]), SPD_fitted[min_id], marker='o', color='black', alpha=1, linestyle = 'None') plt.xlim([0, math.pi]) ax.xaxis.grid(linewidth=1.0) ax.set_yticklabels([]) # ax.set_rticks([0.5, 1, 1.5, 2]) # less radial ticks ax.set_theta_zero_location("N") # ax.set_xticks(np.arange(0,210,30)) # plt.title('Sailing speed') ax.set_xticks(np.radians(np.linspace(0,180,10))) plt.legend(loc='lower left') # sns.despine() with plt.xkcd(): plt.suptitle("Caribbean Rose sailing points @ 8nm winds", fontsize=20) plt.show()
def _draw_chart(self): smooth = 20 filtersize = 8000 myFmt = mdates.DateFormatter('%d.%b %H:%M') watertemp_patch = mpatches.Patch(color='blue', label='Water') airtemp_patch = mpatches.Patch(color='green', label='Air') heater_patch = mpatches.Patch(color='red', label='Heater') humidity_patch = mpatches.Patch(color='blue', label='Humidity') heaterpercentage_patch = mpatches.Patch(color='red', label='Heater Percentage') sun_patch = mpatches.Patch(color='orange', label='Sun') moon_patch = mpatches.Patch(color='blue', label='Moon') data = self._get_cloudant_data() timeval = self._get_keys(data) timedt = self._get_date_time(data) watertemp = self._get_value(data, "watertemp") airtemp = self._get_value(data, "airtemp") heater = self._get_value(data, "heater") heaterspecial = self._get_modified(heater, 0.2, 23) heaterBoolean = self._get_boolean(heater) humidity = self._get_value(data, "humidity") moon = self._get_value(data, "moon") sun = self._get_value(data, "sun") smoothairtemp = [0] * len(timeval) smoothhum = [0] * len(timeval) heaterPercentage = [0] * len(timeval) # smooth the raw values for i in range(smooth, len(timeval) - smooth): airdummy = 0.0 humdummy = 0.0 for j in range(i - smooth, i + smooth): airdummy += airtemp[j] humdummy += humidity[j] airdummy /= (2.0 * smooth) humdummy /= (2.0 * smooth) smoothairtemp[i] = airdummy smoothhum[i] = humdummy for i in range(len(timeval) - smooth, len(timeval)): smoothairtemp[i] = smoothairtemp[len(timeval) - smooth - 1] smoothhum[i] = smoothhum[len(timeval) - smooth - 1] # Calculate heater percentage for i in range(filtersize, len(timeval)): timeOn = 0.0 for m in range(i - filtersize, i): if heaterBoolean[m]: timeOn += timeval[m] - timeval[m - 1] heaterPercentage[i] = ( timeOn / (timeval[i] - timeval[i - filtersize])) * 100 # Temp with plt.xkcd(): duration = 12000 fig = plt.figure(figsize=(20, 15), dpi=256) ax = fig.add_axes((0.035, 0.068, 0.93, 0.93)) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.plot(timedt[-duration:], watertemp[-duration:], 'blue', timedt[-duration:], smoothairtemp[-duration:], 'green', timedt[-duration:], heaterspecial[-duration:], 'red') ax.legend(handles=[watertemp_patch, airtemp_patch, heater_patch]) ax.xaxis.set_major_formatter(myFmt) fig.autofmt_xdate() fig.savefig("temperature.png") # Percentage with plt.xkcd(): duration = 20000 fig = plt.figure(figsize=(20, 15), dpi=256) ax = fig.add_axes((0.035, 0.068, 0.93, 0.93)) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.plot(timedt[-duration:], heaterPercentage[-duration:], 'red', timedt[-duration:], smoothairtemp[-duration:], 'green', timedt[-duration:], smoothhum[-duration:], 'blue') ax.legend(handles=[ heaterpercentage_patch, airtemp_patch, humidity_patch ]) ax.xaxis.set_major_formatter(myFmt) fig.autofmt_xdate() fig.savefig("percentage.png") # sun moon with plt.xkcd(): duration = 70000 fig = plt.figure(figsize=(20, 15), dpi=256) ax = fig.add_axes((0.035, 0.068, 0.93, 0.93)) ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.plot(timedt[-duration:], sun[-duration:], 'orange', timedt[-duration:], moon[-duration:], 'blue') ax.legend(handles=[sun_patch, moon_patch]) ax.xaxis.set_major_formatter(myFmt) fig.autofmt_xdate() fig.savefig("sunmoon.png")
import matplotlib.pyplot as plt import numpy as np dataSet = np.array([ -0.061134, 0.00822, -0.007381, -0.067561, -0.006238, -0.044251, -0.11207, 0.030226, -0.129556, 0.001319, -0.033679, -0.072795, 0.073396, -0.011618, -0.026852, -0.040356, -0.047539, -0.001732, -0.008899, -0.020837, -0.084811, -0.262077, -0.110167, 0.034955, 0.012688, -0.00217, -0.073462, -0.043419, -0.05473, -0.011755, -0.061718, -0.10171, -0.032705, -0.045334, -0.079288, -0.036233, -0.011494, -0.093729, -0.065215, -0.037113, -0.044399, -0.084412, 0.003444, -0.05676, -0.07897, -0.105367, -0.038634, -0.043261, -0.139773, -0.059094, -0.057736, -0.102524, 0.023881, -0.079116, -0.078965, -0.161359, -0.119376, -0.076008, -0.006444, -0.026401 ]) plt.xkcd(dataSet) plt.show()
def main(): pd.options.mode.chained_assignment = None helpStrings = GetHelpStrings() parser = argparse.ArgumentParser() parser.add_argument("-Situation", help=helpStrings["Situation"], nargs='+', type=int) parser.add_argument("-Teams", help=helpStrings["Teams"], nargs='+', type=str) parser.add_argument("-Conferences", help=helpStrings["Conferences"], nargs='+', type=str) parser.add_argument("-tweet", help=helpStrings["tweet"], action='store_true', default=False) parser.add_argument("-GetFieldGoalDecision", help=helpStrings["GetFieldGoalDecision"], action='store_true', default=False) parser.add_argument("-Graph4thAndDistance", help=helpStrings["Graph4thAndDistance"], action='store_true', default=False) parser.add_argument("-GraphTeamPointsPerPossessionByYear", help=helpStrings["GraphTeamPointsPerPossessionByYear"], action='store_true', default=False) parser.add_argument( "-GraphCompareConferencePointsPerPossession", help=helpStrings["GraphCompareConferencePointsPerPossession"], action='store_true', default=False) args = parser.parse_args() #print(args) #set up plot design plt.xkcd() #"End Period", "End Clock", "End Spot" #"4 Play Number", "1 Period Number", "5 Offense Points", "6 Defense Points", "7 Distance", "3 Spot", "8 Play Type", "9 Drive Number", "10 Drive Play" #"1 Period, 2 SecondsLeft, 3 Spot, 4 PlayNumber, 5 OffensePoints, 6 DefensePoints, 7 Distance, 8 PlayType, 9 DriveNumber, 10 DrivePlay" #qtr, time, ballPosition, playNumber, offensePoints, defensePoints, distance, "1", driveNumber, "1", offenseWins, offenseLosses, offenseConferenceStrength, defenseWins, defenseLosses, defenseConferenceStrength, HomeOffense if (args.GetFieldGoalDecision): if (len(args.Situation)) != 17: exit( "If getting a field goal decision must pass the situation for which you are investigating with the -Situation parameter:\n" + helpStrings["Situation"]) fgSituation = args.Situation[:3] + args.Situation[-7:] g4Situation = [args.Situation[3]] + [ args.Situation[0] ] + args.Situation[4:7] + [args.Situation[2]] + args.Situation[8:-1] GetFieldGoalDecision(fgSituation, g4Situation, args.tweet) if (args.GraphCompareConferencePointsPerPossession): if (len(args.Conferences) == 0): exit( "Must include list of conferences using -Conferences to compare with -GraphCompareConferencePointsPerPossession" ) GraphCompareConferencePointsPerPossession(conferences=args.Conferences, tweetResults=args.tweet)
def plot_data(cases, deaths, xvalues, parameters): """ """ cases_model = False deaths_model = False rolling_window = 7 rolling_cases = rolling_mean(cases, rolling_window) rolling_deaths = rolling_mean(deaths, rolling_window) try: cases_popt, _ = curve_fit(covid_curve, xvalues, cases, p0=(-70, 2 * max(rolling_cases), 5, 50)) covid_predict('cases', cases_popt, past=len(xvalues)) cases_model = True except RuntimeError: print("No cases-model due to weird data.") try: deaths_popt, _ = curve_fit(covid_curve, xvalues, deaths, p0=(-60, 2 * max(rolling_deaths), 5, 50)) covid_predict('deaths', deaths_popt, past=len(xvalues)) deaths_model = True except RuntimeError: print("No deaths-model due to weird data.") cases = [max(0, value) for value in cases] deaths = [max(0, value) for value in deaths] location = parameters[LOCATION] if location in PlotExceptions.keys(): location = PlotExceptions[location] font = {'color': 'darkred', 'weight': 'normal', 'size': 16} if parameters[XKCD]: plt.xkcd() else: font[FAMILY] = SERIF # fig, ax = plt.subplots(2, sharex=True) fig, ax = plt.subplots(2, sharex=True, gridspec_kw={'hspace': 0.05}) ax[0].bar(xvalues, cases, label='Daily Cases', width=0.5, color='c') ax[1].bar(xvalues, deaths, label='Daily Deaths', width=0.5, color='r') ax[0].plot(xvalues, rolling_cases, label='Cases ' + str(rolling_window) + '-Day Average', color='c') ax[1].plot(xvalues, rolling_deaths, label='Deaths ' + str(rolling_window) + '-Day Average', color='r') if cases_model: ax[0].plot(xvalues, covid_curve(np.array(xvalues), adjustment=3.5, *cases_popt), label='Cases Model', color='g') if deaths_model: ax[1].plot(xvalues, covid_curve(np.array(xvalues), adjustment=3.5, *deaths_popt), label='Deaths Model', color='g') if deaths_model and cases_model: print() print("{0} has a {1:.2f}% fatality rate, and the lag is {2:.0f} days.". format(location, 100 * deaths_popt[1] / cases_popt[1], deaths_popt[0] - cases_popt[0])) # plot cases given deaths deaths_popt[1] *= 125 # one in 125 die deaths_popt[ 0] -= 16 # die 21 days after infection, symptoms shw up after 5 days (21-5=16) # ax.plot(xvalues, covid_curve(np.array(xvalues), *deaths_popt), color='b') # plot deaths given cases cases_popt[1] /= 125 cases_popt[0] += 16 # ax.plot(xvalues, covid_curve(np.array(xvalues), *cases_popt), color='b') ax[0].label_outer() ax[0].grid() ax[0].legend() ax[1].grid() ax[1].legend() ax[0].set_ylabel('Number of Cases', fontdict=font) ax[1].set_ylabel('Number of Deaths', fontdict=font) plt.xlabel('Days Before ' + parameters[LASTDAY], fontdict=font) # plt.suptitle(location + ': COVID-19 Cases, Deaths', fontdict=font) ax[0].set_title(location + ': COVID-19 Cases, Deaths', fontdict=font) plt.subplots_adjust(left=0.15) # plt.tight_layout(pad=1) # minimal padding if YLIMIT in parameters: if is_float(parameters[YLIMIT]): ax[0].set_ylim(bottom=0, top=float(parameters[YLIMIT])) elif parameters[YLIMIT] == 'deaths': ax[0].set_ylim(bottom=0, top=max(deaths)) else: plt.ylim(bottom=0) else: plt.ylim(bottom=0) if parameters[PDF]: fig.savefig(location + '-covid.pdf') plt.get_current_fig_manager().full_screen_toggle( ) # Make full screen, need to use Qt5 plt.show() # display plot on screen
def test_xkcd_no_cm(): assert mpl.rcParams["path.sketch"] is None plt.xkcd() assert mpl.rcParams["path.sketch"] == (1, 100, 2) np.testing.break_cycles() assert mpl.rcParams["path.sketch"] == (1, 100, 2)
def test_xkcd_cm(): assert mpl.rcParams["path.sketch"] is None with plt.xkcd(): assert mpl.rcParams["path.sketch"] == (1, 100, 2) assert mpl.rcParams["path.sketch"] is None
arrowprops=dict(facecolor='black', shrink=0.05) ) # Save JPG-file pil_kwargs = {'quality': 90} plt.savefig(out_file, dpi=200, pil_kwargs=pil_kwargs) # Save the same file in SVG-format svg_file = out_file.replace('jpg', 'svg') plt.savefig(svg_file) print(f'Saved {out_file} and {svg_file}') plt.show() plt.close() # Now re-generate the plot in a "funny"-style, and save the file # with "_funny" added to the JPG filename with plt.xkcd(): # Plot it plt.plot(t,x) plt.axhline(yi, ls='dotted') # Annotate it plt.annotate('This is\nfunny!', xy = (xi,yi), xytext = (xi-dx, yi-dy), arrowprops=dict(facecolor='black', shrink=0.05) ) funny_file = out_file.replace('.jpg', '_funny.jpg') plt.savefig(funny_file, dpi=200, pil_kwargs=pil_kwargs) print(f'... and also saved {funny_file} ;)') plt.show()
from matplotlib import pyplot as plt plt.style.use('ggplot') # estilo del grafico plt.xkcd() # estilo del grafico # defino dos listas ages_x = [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35] # defino otra lista py_dev_y = [45372, 48876, 53850, 57287, 63016, 65998, 70003, 70000, 71496, 75370, 83640] # ocurre lo mismo que en el caso anterior # el marker define el tipo de punteado que va a tener el grafico en cada uno de sus puntos plt.plot(ages_x,py_dev_y, label="Python") # la letra b define el color de la linea # lista java script js_dev_y = [37810, 43515, 46823, 49293, 53437, 56373, 62375, 66674, 68745, 68746, 74583] plt.plot(ages_x,js_dev_y,label="JavaScript") # la letra b define el color de la linea dev_y = [38496, 42000, 46752, 49320, 53200, 56000, 62316, 64928, 67317, 68748, 73752] # ocurre lo mismo que en el caso anterior # el marker define el tipo de punteado que va a tener el grafico en cada uno de sus puntos plt.plot(ages_x,dev_y,color='#444444', linestyle='--', label='All Devs') # el k define un color y los guiones que sea una linea segmentada
def main(): get_args() # parse input args if args.input == STDIN_FNAME: fin = sys.stdin else: fin = open(args.input) all_inputs = fin.readlines() if args.input != STDIN_FNAME: fin.close() # parse column format nr_column = len(all_inputs[0].rstrip().split()) if args.column is None: column = ['y'] * nr_column else: column = args.column.strip().split(',') for k in column: assert k[0] in ['x', 'y'] assert nr_column == len( column), "Column and data doesn't have same length. {}!={}".format( nr_column, len(column)) args.y_column = [v for v in column if v[0] == 'y'] args.y_column_idx = [idx for idx, v in enumerate(column) if v[0] == 'y'] args.x_column = [v for v in column if v[0] == 'x'] args.x_column_idx = [idx for idx, v in enumerate(column) if v[0] == 'x'] nr_x_column = len(args.x_column) nr_y_column = len(args.y_column) if nr_x_column > 1: assert nr_x_column == nr_y_column, \ "If multiple x columns are used, nr_x_column must equals to nr_y_column" x_column_set = set(args.x_column) # read and parse data data = [[] for _ in range(nr_column)] ended = defaultdict(bool) data_format = -1 for lineno, line in enumerate(all_inputs): line = line.rstrip('\n').split(args.delimeter) assert len(line) <= nr_column, \ """One row have too many columns (separated by {})! Line: {}""".format(repr(args.delimeter), line) for idx, val in enumerate(line): if val == '': ended[idx] = True continue else: val = float(val) assert not ended[idx], "Column {} has hole!".format(idx) data[idx].append(val) data_ys = [data[k] for k in args.y_column_idx] max_ysize = max([len(t) for t in data_ys]) print "Size of the longest y column: ", max_ysize if nr_x_column: data_xs = [data[k] for k in args.x_column_idx] else: data_xs = [list(range(max_ysize))] for idx, data_y in enumerate(data_ys): data_ys[idx] = np.asarray(data_y) if args.decay != 0: data_ys[idx] = exponential_smooth(data_y, args.decay) #if idx == 0: # TODO allow different decay for each y #data_ys[idx] = exponential_smooth(data_y, 0.5) for idx, data_x in enumerate(data_xs): data_xs[idx] = np.asarray(data_x) if args.xkcd: with plt.xkcd(): do_plot(data_xs, data_ys) else: do_plot(data_xs, data_ys)
def compute_isi_fits(all_data): print('Performing the ISI fitting analysis') plt.xkcd() plt.figure(figsize=(15, 10)) for d in all_data: bins = np.linspace(0, 0.2, 200) # bins = 2500 h = plt.hist(all_data[d]['isi'], histtype='step', density=1, cumulative=False, bins=bins, label=d, color=d, lw=2) # plt.xlim(0, 0.1) # plt.ylim(1.e0, None) plt.legend(loc='best') plt.savefig('plots/isi_overview.pdf') plt.savefig('plots/isi_overview.png') plt.show() plt.figure(figsize=(10, 10)) for d in all_data: bins = np.linspace(0, 0.1, 100) # bins = 2500 h = plt.hist(all_data[d]['isi'], histtype='step', density=1, cumulative=1, bins=bins, label=d, color=d) H = h[0] b = (h[1][:-1] + h[1][1:]) / 2. popt, pcov = curve_fit(exp_func, b, H) plt.plot(b, exp_func(b, *popt), color=d, ls=':') all_data[d]['exp_diff_fit'] = np.sum((H - exp_func(b, *popt))**2.) popt, pcov = curve_fit(gamma_func, b, H) plt.plot(b, gamma_func(b, *popt), color=d, ls='--') all_data[d]['gamma_diff_fit'] = np.sum((H - gamma_func(b, *popt))**2.) # plt.xlim(0, 0.1) # plt.ylim(1.e0, None) plt.legend(loc='best') plt.savefig('plots/isi_fit.pdf') plt.savefig('plots/isi_fit.png') plt.show() plt.figure() for i, d in enumerate(all_data): plt.bar(i, all_data[d]['exp_diff_fit'], color=d) plt.ylabel(r'$L_2$ error') plt.xticks([]) plt.yticks([]) plt.title('Exponential fit') plt.tight_layout() plt.savefig('plots/isi_poisson_fit.pdf') plt.savefig('plots/isi_poisson_fit.png') plt.show() plt.figure() for i, d in enumerate(all_data): plt.bar(i, all_data[d]['gamma_diff_fit'], color=d) plt.ylabel(r'$L_2$ error') plt.xticks([]) plt.yticks([]) plt.title('Gamma fit') plt.tight_layout() plt.savefig('plots/isi_gamma_fit.pdf') plt.savefig('plots/isi_gamma_fit.png') plt.show()
def run(args): import os import sys import numpy as np import evo.core.lie_algebra as lie from evo.core import trajectory from evo.core.trajectory import PoseTrajectory3D from evo.tools import file_interface, log from evo.tools.settings import SETTINGS log.configure_logging(verbose=args.verbose, silent=args.silent, debug=args.debug) if args.debug: import pprint logger.debug( "main_parser config:\n" + pprint.pformat({arg: getattr(args, arg) for arg in vars(args)}) + "\n") logger.debug(SEP) trajectories = [] ref_traj = None if args.subcommand == "tum": for traj_file in args.traj_files: if traj_file != args.ref: trajectories.append( (traj_file, file_interface.read_tum_trajectory_file(traj_file))) if args.ref: ref_traj = file_interface.read_tum_trajectory_file(args.ref) elif args.subcommand == "kitti": for pose_file in args.pose_files: if pose_file != args.ref: trajectories.append( (pose_file, file_interface.read_kitti_poses_file(pose_file))) if args.ref: ref_traj = file_interface.read_kitti_poses_file(args.ref) elif args.subcommand == "euroc": for csv_file in args.state_gt_csv: if csv_file != args.ref: trajectories.append( (csv_file, file_interface.read_euroc_csv_trajectory(csv_file))) if args.ref: ref_traj = file_interface.read_euroc_csv_trajectory(args.ref) elif args.subcommand == "bag": import rosbag bag = rosbag.Bag(args.bag) try: if args.all_topics: topic_info = bag.get_type_and_topic_info() topics = sorted([ t for t in topic_info[1].keys() if topic_info[1][t][0] == "geometry_msgs/PoseStamped" and t != args.ref ]) if len(topics) == 0: logger.error("no geometry_msgs/PoseStamped topics found!") sys.exit(1) else: topics = args.topics if not topics: logger.warning( "no topics used - specify topics or use the --all_topics flag" ) sys.exit(1) for topic in topics: trajectories.append( (topic, file_interface.read_bag_trajectory(bag, topic))) if args.ref: ref_traj = file_interface.read_bag_trajectory(bag, args.ref) finally: bag.close() else: raise RuntimeError("unsupported subcommand: " + args.subcommand) if args.merge: if args.subcommand == "kitti": raise TypeError( "can't merge KITTI files - but you can append them with 'cat'") if len(trajectories) == 0: raise RuntimeError("no trajectories to merge (excluding --ref)") merged_stamps = trajectories[0][1].timestamps merged_xyz = trajectories[0][1].positions_xyz merged_quat = trajectories[0][1].orientations_quat_wxyz for _, traj in trajectories[1:]: merged_stamps = np.concatenate((merged_stamps, traj.timestamps)) merged_xyz = np.concatenate((merged_xyz, traj.positions_xyz)) merged_quat = np.concatenate( (merged_quat, traj.orientations_quat_wxyz)) order = merged_stamps.argsort() merged_stamps = merged_stamps[order] merged_xyz = merged_xyz[order] merged_quat = merged_quat[order] trajectories = [("merged_trajectory", PoseTrajectory3D(merged_xyz, merged_quat, merged_stamps))] if args.transform_left or args.transform_right: tf_type = "left" if args.transform_left else "right" tf_path = args.transform_left if args.transform_left else args.transform_right t, xyz, quat = file_interface.load_transform_json(tf_path) logger.debug(SEP) if not lie.is_se3(t): logger.warning("not a valid SE(3) transformation!") if args.invert_transform: t = lie.se3_inverse(t) logger.debug("applying a " + tf_type + "-multiplicative transformation:\n" + str(t)) for name, traj in trajectories: traj.transform(t, right_mul=args.transform_right) if args.t_offset: logger.debug(SEP) for name, traj in trajectories: if type(traj) is trajectory.PosePath3D: logger.warning( "{} doesn't have timestamps - can't add t_offset".format( name)) else: logger.info("adding time offset to {}: {} (s)".format( name, args.t_offset)) traj.timestamps += args.t_offset if args.align or args.correct_scale: if not args.ref: logger.debug(SEP) logger.warning("can't align without a reference! (--ref) *grunt*") else: if args.subcommand == "kitti": traj_tmp, ref_traj_tmp = trajectories, [ ref_traj for n, t in trajectories ] else: traj_tmp, ref_traj_tmp = [], [] from evo.core import sync for name, traj in trajectories: logger.debug(SEP) ref_assoc, traj_assoc = sync.associate_trajectories( ref_traj, traj, max_diff=args.t_max_diff, first_name="ref", snd_name=name) ref_traj_tmp.append(ref_assoc) traj_tmp.append((name, traj_assoc)) trajectories = traj_tmp correct_only_scale = args.correct_scale and not args.align trajectories_new = [] for nt, ref_assoc in zip(trajectories, ref_traj_tmp): logger.debug(SEP) logger.debug("aligning " + nt[0] + " to " + args.ref + "...") trajectories_new.append( (nt[0], trajectory.align_trajectory(nt[1], ref_assoc, args.correct_scale, correct_only_scale, args.n_to_align))) trajectories = trajectories_new for name, traj in trajectories: print_traj_info(name, traj, args.verbose, args.full_check) if args.ref: print_traj_info(args.ref, ref_traj, args.verbose, args.full_check) if args.plot or args.save_plot or args.serialize_plot: from evo.tools.plot import PlotMode plot_mode = PlotMode.xyz if not args.plot_mode else PlotMode[ args.plot_mode] import numpy as np from evo.tools import plot import matplotlib.pyplot as plt import matplotlib.cm as cm plot_collection = plot.PlotCollection("evo_traj - trajectory plot") fig_xyz, axarr_xyz = plt.subplots(3, sharex="col", figsize=tuple(SETTINGS.plot_figsize)) fig_rpy, axarr_rpy = plt.subplots(3, sharex="col", figsize=tuple(SETTINGS.plot_figsize)) fig_traj = plt.figure(figsize=tuple(SETTINGS.plot_figsize)) if (args.align or args.correct_scale) and not args.ref: plt.xkcd(scale=2, randomness=4) fig_traj.suptitle("what if --ref?") fig_xyz.suptitle("what if --ref?") ax_traj = plot.prepare_axis(fig_traj, plot_mode) if args.ref: short_traj_name = os.path.splitext(os.path.basename(args.ref))[0] if SETTINGS.plot_usetex: short_traj_name = short_traj_name.replace("_", "\\_") plot.traj(ax_traj, plot_mode, ref_traj, '--', 'grey', short_traj_name, alpha=0 if SETTINGS.plot_hideref else 1) plot.traj_xyz(axarr_xyz, ref_traj, '--', 'grey', short_traj_name, alpha=0 if SETTINGS.plot_hideref else 1) plot.traj_rpy(axarr_rpy, ref_traj, '--', 'grey', short_traj_name, alpha=0 if SETTINGS.plot_hideref else 1) cmap_colors = None if SETTINGS.plot_multi_cmap.lower() != "none": cmap = getattr(cm, SETTINGS.plot_multi_cmap) cmap_colors = iter(cmap(np.linspace(0, 1, len(trajectories)))) for name, traj in trajectories: if cmap_colors is None: color = next(ax_traj._get_lines.prop_cycler)['color'] else: color = next(cmap_colors) short_traj_name = os.path.splitext(os.path.basename(name))[0] if SETTINGS.plot_usetex: short_traj_name = short_traj_name.replace("_", "\\_") plot.traj(ax_traj, plot_mode, traj, '-', color, short_traj_name) if args.ref and isinstance(ref_traj, trajectory.PoseTrajectory3D): start_time = ref_traj.timestamps[0] else: start_time = None plot.traj_xyz(axarr_xyz, traj, '-', color, short_traj_name, start_timestamp=start_time) plot.traj_rpy(axarr_rpy, traj, '-', color, short_traj_name, start_timestamp=start_time) plt.tight_layout() plot_collection.add_figure("trajectories", fig_traj) plot_collection.add_figure("xyz_view", fig_xyz) plot_collection.add_figure("rpy_view", fig_rpy) if args.plot: plot_collection.show() if args.save_plot: logger.info(SEP) plot_collection.export(args.save_plot, confirm_overwrite=not args.no_warnings) if args.serialize_plot: logger.info(SEP) plot_collection.serialize(args.serialize_plot, confirm_overwrite=not args.no_warnings) if args.save_as_tum: logger.info(SEP) for name, traj in trajectories: dest = os.path.splitext(os.path.basename(name))[0] + ".tum" file_interface.write_tum_trajectory_file( dest, traj, confirm_overwrite=not args.no_warnings) if args.ref: dest = os.path.splitext(os.path.basename(args.ref))[0] + ".tum" file_interface.write_tum_trajectory_file( dest, ref_traj, confirm_overwrite=not args.no_warnings) if args.save_as_kitti: logger.info(SEP) for name, traj in trajectories: dest = os.path.splitext(os.path.basename(name))[0] + ".kitti" file_interface.write_kitti_poses_file( dest, traj, confirm_overwrite=not args.no_warnings) if args.ref: dest = os.path.splitext(os.path.basename(args.ref))[0] + ".kitti" file_interface.write_kitti_poses_file( dest, ref_traj, confirm_overwrite=not args.no_warnings) if args.save_as_bag: logger.info(SEP) import datetime import rosbag dest_bag_path = str( datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S.%f')) + ".bag" logger.info("saving trajectories to " + dest_bag_path + "...") bag = rosbag.Bag(dest_bag_path, 'w') try: for name, traj in trajectories: dest_topic = os.path.splitext(os.path.basename(name))[0] frame_id = traj.meta[ "frame_id"] if "frame_id" in traj.meta else "" file_interface.write_bag_trajectory(bag, traj, dest_topic, frame_id) if args.ref: dest_topic = os.path.splitext(os.path.basename(args.ref))[0] frame_id = ref_traj.meta[ "frame_id"] if "frame_id" in ref_traj.meta else "" file_interface.write_bag_trajectory(bag, ref_traj, dest_topic, frame_id) finally: bag.close()
def main(): np.random.seed(42) # Prepare Data to Plot x = np.arange(1, 5, 0.1) err = np.random.randn(len(x)) y = 2 * x + 3 + err X = np.matrix(x).T X = sm.add_constant(X) Y = np.matrix(y).T ols = OLSEstimator(X, Y) ols.estimate() ols.test() print("OLS: ") ols.summary() with plt.xkcd(): # Prepare Plot plt.figure(figsize=(10, 6), dpi=300) plt.title(r"Simple OLS & Ridge", fontsize=16) plt.xlabel(r'x', fontsize=14) plt.ylabel(r'y', fontsize=14) # Plot with Legends plt.scatter(x, y, label='Data') plt.plot(x, np.asarray(ols.y_hat).ravel(), 'r', label='OLS') # Other options plt.legend(fontsize=12) plt.savefig("simple_ols.png", dpi=300) # Prepare Data to Plot x1 = np.arange(1, 5, 0.1) x2 = x1**2 err = np.random.rand(len(x1)) y = 2 * x2 + 3 * x1 + 5 + 5 * err X1 = np.matrix(np.column_stack((x1, x2))) X1 = sm.add_constant(X1) X2 = np.matrix(x1).T X2 = sm.add_constant(X2) Y = np.matrix(y).T ols_1 = OLSEstimator(X1, Y) ols_2 = OLSEstimator(X2, Y) ols_1.estimate() ols_2.estimate() ols_1.test() ols_2.test() print() print("OLS1: ") ols_1.summary() print() print("OLS2: ") ols_2.summary() f = ols_1.f_test(ols_2) print() print("F-Test: ", f) with plt.xkcd(): # Prepare Plot plt.figure(figsize=(10, 6), dpi=300) plt.title(r"Two OLS", fontsize=16) plt.xlabel(r'x', fontsize=14) plt.ylabel(r'y', fontsize=14) # Plot with Legends plt.scatter(x1, y, label='Data') plt.plot(x1, np.asarray(ols_1.y_hat).ravel(), 'r', alpha=0.7, label='OLS1') plt.plot(x1, np.asarray(ols_2.y_hat).ravel(), 'g', alpha=0.7, label='OLS2') # Other options plt.legend(fontsize=12) plt.savefig("two_ols.png", dpi=300)
async def activity(self, ctx, **flags): messages = [] ticks = [] delta = dt.timedelta(days=1) index = 0 end = datetime.now().date() interval = flags['interval'] user = flags['user'] epoch = dt.date(2019, 1, 11) # This is when the server was created if interval is None: interval = (end - epoch) / delta if interval > (end - epoch) / delta: await ctx.send( f'Too big interval (max size: `{(end - epoch) // delta}`)') return if user is None: user = ctx.author cursor = cfg.db.cursor() cursor.execute(f''' SELECT date(message_date) as date, COUNT(*) AS number FROM messages WHERE date(message_date) BETWEEN "{str(dt.date.today() - dt.timedelta(interval - 1))}" AND "{str(dt.date.today())}" and discord_user_id = {user.id} GROUP BY discord_user_id, DATE(message_date) ORDER BY DATE(message_date), discord_user_id; ''') result = cursor.fetchall() plt.style.use('ggplot') start = end - (interval - 1) * delta while start <= end: if len(result) > index and result[index][0] == str(start): messages.append(result[index][1]) index += 1 else: messages.append(0) if interval > 70: ticks.append(str(start)[:7] if start.day == 1 else None) else: ticks.append(str(start)[5:] if start.weekday() == 0 else None) start += delta x_pos = [i for i, _ in enumerate(messages)] print(x_pos) print(messages) if interval > 50: # With a lot of data to display cool formatting is less necessary plt.figure(figsize=(24, 13.5)) plt.xkcd(scale=0, randomness=0, length=0) else: plt.xkcd(scale=0.5, randomness=0.5) plt.figure(figsize=(8, 6)) plt.bar(x_pos, messages, color='green') plt.xlabel("Date") plt.ylabel("Messages") plt.title(f"{user.display_name}'s Activity") plt.axhline(y=10, linewidth=1, color='r') plt.subplots_adjust(bottom=0.15) plt.xticks(x_pos, ticks) fname = f'data/{datetime.now().isoformat()}.png' plt.savefig(fname) await ctx.send(file=discord.File(open(fname, 'rb'))) plt.clf() plt.close('all')
from matplotlib import pyplot as plt # plt.style.use("fivethirtyeight") plt.xkcd() # comic sytle for non serious style # Ages 18 to 55 ages_x = [ 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41,
from matplotlib import pyplot as plt # print(plt.style.available) # plt.style.use('fivethirtyeight') # ggplot plt.xkcd() # xkcd comics style ages_x = [1, 2, 3] dev_y = [4, 5, 6] plt.plot( ages_x, dev_y, color="#5a7d9a", linestyle="--", marker=".", linewidth=3, label="All Devs", ) # label is used to specify legend py_dev_y = [4.4, 5.5, 6.6] plt.plot(ages_x, py_dev_y, label="Python") # plt.legend(['All Devs', 'Python']) # add a list of legends for each plot in the order that they are plotted js_dev_y = [10, 20, 30] plt.plot(ages_x, js_dev_y, label="JavaScript") plt.xlabel("Ages") plt.ylabel("Median Salary") plt.title("Median Salary (USD) by Age") plt.legend()
if getenv('DEBUGMEMORY', 'False') == 'True' and __name__ == '__main__': print("====> TURNING DEBUGMEMORY MODE ON <=====") debug_memory = True if getenv('SAVEALL', 'False') == 'True' and __name__ == '__main__': print("====> SAVING FIGURES <=====") saveallfigs = True import matplotlib as mpl FIGSIZE = (19.80, 10.80) #: Figure size, in inches! # FIGSIZE = (16, 9) #: Figure size, in inches! mpl.rcParams['figure.figsize'] = FIGSIZE if getenv('XKCD', 'False') == 'True' and interactive and not saveallfigs: import matplotlib.pyplot as plt plt.xkcd( ) # XXX turn on XKCD-like style ?! cf. http://matplotlib.org/xkcd/ for more details # FIXED try to switch to a non interactive backend when running without DEBUG=True # https://matplotlib.org/api/matplotlib_configuration_api.html?highlight=matplotlib%20use#matplotlib.use if not interactive: import matplotlib print( "Warning: Non interactive simulations, switching from '{}' backend to 'agg'..." .format(matplotlib.get_backend())) # DEBUG matplotlib.use("agg", warn=True, force=True) # else: # import matplotlib # matplotlib.use("TkAgg") if __name__ == '__main__': # Update configuration
def lambda_handler(event, context): params = { 'region': 'us-east-2', 'athena_bucket': 'BUCKETNAME', 'athena_prefix': 'athena-results', 'output_bucket': 'home.example.com' } query_params_24hr = { 'path': 'iot-pool-24-hours' } queryExecutionId = event['detail']['queryExecutionId'] queryRegion = event['region'] athena = boto3.client('athena', region_name=queryRegion) response = athena.get_query_execution(QueryExecutionId=queryExecutionId) s3_path = response['QueryExecution']['ResultConfiguration']['OutputLocation'] filename = re.findall('.*\/(.*)', s3_path)[0] s3 = boto3.resource('s3') obj = s3.Object( params['athena_bucket'], f"{params['athena_prefix']}/{query_params_24hr['path']}/{filename}") csv = obj.get()['Body'].read().decode('utf-8') if query_params_24hr['path'] in s3_path: df = pd.read_table(StringIO(csv), sep=',', dtype={ 'fahrenheit': float, 'time': object }) df.time = pd.to_datetime( df.time, format='%Y-%m-%d %H:%M:%S.%f %Z', errors='coerce') plt.clf() plt.cla() plt.xkcd() ax = plt.gca() df.plot(kind='line', x='time', y='fahrenheit', ax=ax, legend=None) ax.xaxis.set_major_formatter(DateFormatter('%a %l%p', timezone('US/Eastern'))) ax.set_xlabel('') ax.set_ylabel('') dflast = df.tail(1).index[0] ylast = df.fahrenheit[dflast].round(decimals=1) xlast = df.time[dflast] ax.annotate(ylast, xy=(xlast, ylast)) plt.title('Last 24 Hours Pool Temperature') outfile = '/tmp/last-24-hours.png' if os.path.isfile(outfile): os.remove(outfile) plt.savefig(outfile) s3.Bucket(params['output_bucket']).upload_file(outfile, 'last-24-hours.png') return { 'statusCode': 200 # 'body': json.dumps('Hello from Lambda!') }
import numpy as npy import matplotlib.pyplot as plt x = npy.linspace( 0, 5, 10 ) # set x as a set with 10 elements, every elements has the same difference to the previous one. y = 2**x # set y as a set with the same amount of elements of x, and each of them is 2 to the power of x. plt.figure(1) # switch to graph 1. plt.scatter(x, y) # draw only points on the x-y plane. plt.figure(2) # switch to graph 2. plt.plot(x, y) # link those points with lines. with plt.xkcd(): # comic style! plt.figure(3) # switch to graph 3. plt.scatter(x, y) # draw only points on the x-y plane. plt.figure(4) # switch to graph 4. plt.plot(x, y) # link those points with lines. # switch back to normal. plt.figure(5) # switch to graph 5. plt.plot(x, y) # link those points with lines.
sls_t_padded = np.flipud(sls_t_padded) # we want convolution NOT correlation! e = sigmoid(t - 150.0) - sigmoid(t - 500.0) de_dt = sigmoid_grad(t, 150.0) - sigmoid_grad(t, 500.0) convolved = np.multiply( np.convolve(sls_t, de_dt, mode='full')[0:len(t)], np.gradient(t)) ############ # plotting # ############ # global set up grepeat = True with pl.xkcd(): fig, axarr = pl.subplots(2, 2) # axarr[0,0] set up e_line, = axarr[0, 0].plot(t, e, "-", label="strain load", color="#566573") de_line00, = axarr[0, 0].plot(t, de_dt, "--", label="d(strain)/dt", color="#3385ff") dotfollow_line, = axarr[0, 0].plot(t[0], e[0], "o", color="#dc7633") axarr[0, 0].legend(loc='lower left') axarr[0, 0].set_xlim(0, 1000) axarr[0, 0].set_ylim(-0.4, 1.2)
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from math import floor, ceil from pylab import rcParams %matplotlib inline sns.set(style='ticks', palette='Spectral', font_scale=1.5) material_palette = ["#4CAF50", "#2196F3", "#9E9E9E", "#FF9800", "#607D8B", "#9C27B0"] sns.set_palette(material_palette) rcParams['figure.figsize'] = 16, 8 plt.xkcd(); random_state = 42 np.random.seed(random_state) tf.set_random_seed(random_state) math_df = pd.read_csv("data/student/student-mat.csv", sep=";") port_df = pd.read_csv("data/student/student-por.csv", sep=";") math_df["course"] = "math" port_df["course"] = "portuguese" merged_df = math_df.append(port_df) merged_df.shape merge_vector = ["school","sex","age","address", "famsize","Pstatus","Medu","Fedu",