def gen_bars(data, headers, datasets, methods): """ Description: Inputs: Outputs: """ width = 0.5 x = np.arange(0, 16, 2) labels_x = datasets.copy() labels_x.insert(0,"") fig, ax = plt.subplots() bar1 = ax.bar(x - (0.3 + width/2), data[0,:], width, label = methods[0]) add_labels(ax, bar1) if (len(methods) > 1): bar2 = ax.bar(x , data[1,:], width, label = methods[1]) add_labels(ax, bar2) if (len(methods) > 2): bar3 = ax.bar(x + (0.3 + width/2), data[1,:], width, label = methods[2]) add_labels(ax, bar3) ax.set_ylabel(metric) ax.set_xlabel("Dataset") ax.set_xticklabels(labels_x) ax.set_title(metric + " Across Datasets") ax.legend(bbox_to_anchor=(1, 1.15), fancybox=True, framealpha=0.5)
def plotmeshval(val,ixmin=None,ixmax=None,iymin=None,iymax=None, r_min=None,r_max=None,z_min=None,z_max=None,title=None,units=None, block=True): """ plotmeshval(val,ixmin=<int>,ixmax=<int>,iymin=<int>,iymax=<int> title=<string>,units=<string>,block=<True|False>) Display 2-D quantity using polyfill. where ixmin, ixmax, iymin, and iymax are integer variables or expressions used to plot a portion of the grid. title is used as both the title and the figure name. Units are displayed in the side colorbar. Block default is True. The plot axis limits may be specified with r_rmin,r_max,z_min,z_max. """ if ixmin == None: ixmin = com.nxomit if ixmax == None: ixmax = (com.nxm-1) if iymin == None: iymin = 0 if iymax == None: iymax = (com.ny-1) if r_min == None: r_min = com.rm.min() if r_max == None: r_max = com.rm.max() if z_min == None: z_min = com.zm.min() if z_max == None: z_max = com.zm.max() rcdefaults() if title == None: title='Uedge' fig, ax = plt.subplots() verts = np.array([]) z = np.array([]) for ix in range(ixmax-ixmin+1): for iy in range(iymax-iymin+1): v = [] v.append([com.rm[ix,iy,1],com.zm[ix,iy,1]]) v.append([com.rm[ix,iy,2],com.zm[ix,iy,2]]) v.append([com.rm[ix,iy,4],com.zm[ix,iy,4]]) v.append([com.rm[ix,iy,3],com.zm[ix,iy,3]]) verts = np.append(verts,v) z = np.append(z,val[ix,iy]) verts = verts.reshape(len(z),4,2) ax.set_title(title) ax.set_ylabel('Z (m)') ax.set_xlabel('R (m)') ax.set_aspect('equal') coll = PolyCollection(verts,array=z,cmap=cm.jet,edgecolors='face') ax.add_collection(coll) ax.autoscale_view() cbar = fig.colorbar(coll,ax=ax) #if units != None: cbar.ax.set_ylabel(units,rotation=-90,va='bottom') if units != None: cbar.ax.set_ylabel(units,va='bottom') plt.ylim(z_min,z_max) plt.xlim(r_min,r_max) #plt.show(block=block) plt.ion() plt.show() plt.pause(0.001)
def club_tags(unencoded_clubs_list): """ Creates a bar graph showing of the number of occurrances of each possible club tag. By using a dictionary to count club tag occurrances, the function then creates a matplotlib bar graph using numpy representations of the dictionary information. The graph is formatted and pushed as a Response type for view on the server. Returns: -------- Response The graph """ club_dict = {} for clubs in unencoded_clubs_list: for tag in clubs.get_category(): if tag in club_dict: club_dict[tag] = club_dict[tag] + 1 else: club_dict[tag] = 1 x = np.zeros(len(club_dict)) index_counter = 0 for tag in club_dict: x[index_counter] = club_dict.get(tag) index_counter = index_counter + 1 fig = plt.figure() ax = fig.add_subplot() bar = ax.bar(np.arange(len(club_dict)), x) labels = club_dict.keys() ax.set_xticks(np.arange(len(club_dict))) ax.set_xticklabels(labels, rotation='45', ha='right') ax.set_xlabel('Club Tags') ax.set_ylabel('Number of Occurrances') ax.set_title('Number of Club Tag Occurrances') for rect in bar: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), textcoords="offset points", ha='center', va='bottom') plt.tight_layout() output = io.BytesIO() FigureCanvas(fig).print_png(output) return Response(output.getvalue(), mimetype='image/png')
def draw(self, ax, output_mode): self.colorize_default_lines() for p in self.plots: p.draw(ax) if self.show_legend: leg = ax.legend(**self.legend_kwargs) if output_mode == "png": #latex output doesn't support alpha leg.get_frame().set_alpha(0.5) plt.setp(leg.get_texts(), fontsize='small') ax.xaxis.set_label_text(self.x_axis_desc.label) ax.yaxis.set_label_text(self.y_axis_desc.label) ax.set_ybound(self.y_axis_desc.range_min, self.y_axis_desc.range_max) ax.set_xbound(self.x_axis_desc.range_min, self.x_axis_desc.range_max) ax.set_title(self.title)
def draw(self,ax,output_mode): self.colorize_default_lines() for p in self.plots: p.draw(ax); if self.show_legend: leg=ax.legend(**self.legend_kwargs) if output_mode == "png": #latex output doesn't support alpha leg.get_frame().set_alpha(0.5); plt.setp(leg.get_texts(), fontsize='small') ax.xaxis.set_label_text(self.x_axis_desc.label) ax.yaxis.set_label_text(self.y_axis_desc.label) ax.set_ybound(self.y_axis_desc.range_min,self.y_axis_desc.range_max) ax.set_xbound(self.x_axis_desc.range_min,self.x_axis_desc.range_max) ax.set_title(self.title)
def clubs_per_user(user_list): """ Creates a bar graph of the number of clubs per user. Using a dictionary to gather each user's name and the number of club each user is in, numpy representations of the data is used to create a matplotlib bar graph. The graph is then formatted and pushed for view on the server. Returns: -------- Response The graph """ user_club_dict = {} for user in user_list: name = user.get_user_name() user_club_dict[name] = len(user.get_user_clubs()) x = np.zeros(len(user_club_dict)) index_counter = 0 for user in user_club_dict: x[index_counter] = user_club_dict.get(user) index_counter = index_counter + 1 fig = plt.figure() ax = fig.add_subplot() bar = ax.bar(np.arange(len(user_club_dict)), x) labels = user_club_dict.keys() ax.set_xticks(np.arange(len(user_club_dict))) ax.set_xticklabels(labels, rotation='45', ha='right') ax.set_xlabel('User Name') ax.set_ylabel('Number of Clubs') ax.set_title('Number of Clubs per User') for rect in bar: height = rect.get_height() ax.annotate('{}'.format(height), xy=(rect.get_x() + rect.get_width() / 2, height), xytext=(0, 3), textcoords="offset points", ha='center', va='bottom') plt.tight_layout() output = io.BytesIO() FigureCanvas(fig).print_png(output) return Response(output.getvalue(), mimetype='image/png')
def plot_graph(train_history, label_col, mode): # Obtain scores from history loss = train_history.history['loss'] #List val_loss = train_history.history['val_loss'] #Check if binary or multiclass problem to obtain correct metrics if mode == 0: acc = train_history.history['binary_accuracy'] val_acc = train_history.history['val_binary_accuracy'] else: acc = train_history.history['categorical_accuracy'] val_acc = train_history.history['val_categorical_accuracy'] # Plot loss scores sns.set_style("whitegrid") fig, ax = plt.subplots(1, 1) ax.plot(loss, label = "Loss") ax.plot(val_loss, label = "Validation Loss") ax.set_title('Model Loss') ax.legend(loc = "upper right") ax.set_xlim([0, 100]) ax.set_ylabel("Loss") ax.set_xlabel("Epochs") ax.minorticks_on() ax.grid(b=True, which='major') ax.grid(b=True, which='minor') plt.savefig(results_dir + '/' + label_col + '_loss.png') plt.show() # Plot accuracy scores fig, ax = plt.subplots(1, 1) ax.plot(acc, label = "Accuracy") ax.plot(val_acc, label = "Validation Accuracy") ax.set_title('Model Accuracy') ax.legend(loc = "lower right") ax.set_xlim([0, 100]) ax.grid(b=True, which='major') ax.grid(b=True, which='minor') ax.set_ylabel("Accuracy") ax.set_xlabel("Epochs") ax.minorticks_on() plt.savefig(results_dir + '/' + label_col + '_acc.png') plt.show() return 0
dict['sdl'] = social_distancing_level return dict # --------------------------------MAIN CODE------------------------------------ os.system('clear') settings = setup() title = settings['title'] social_distancing = settings['sd'] social_distancing_lvl = settings['sdl'] ax.set_title(title) people = [] # people is a global variable for i in range(0, 100): if social_distancing == True: if i % social_distancing_lvl == 0: bool = True else: bool = False else: bool = False person = Person(i, bool) person.init_draw() people.append(person)
import numpy as np import matplotlib.pyplot as plt import matplotlib.axes as ax import pylab # change to proper directory os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis') # load file, select proper date range, convert row to numeric dtypes hpc = pd.read_csv('household_power_consumption.txt', sep=';', index_col=['Date'], usecols=['Global_active_power', 'Date']) hpc = hpc['1/2/2007':'2/2/2007'].convert_objects(convert_numeric=True) # create plotting variables y = pd.value_counts(hpc.Global_active_power, bins=np.arange(0, 8, 0.5), sort=False) index = y.index fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.bar(index, y, width=0.5, color='r') ax.set_xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Frequency') ax.set_title('Global Active Power') pylab.show() # hpc[hpc['Global_active_power'] > 4]
# import needed libraries import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.axes as ax import pylab # change to proper directory os.chdir('C:\Users\Matt\Desktop\Python Projects\Exploratory Data Analysis') # load file, select proper date range, convert row to numeric dtypes hpc = pd.read_csv('household_power_consumption.txt', sep=';', index_col=['Date'], usecols=['Global_active_power', 'Date']) hpc = hpc['1/2/2007':'2/2/2007'].convert_objects(convert_numeric=True) # create plotting variables y = pd.value_counts(hpc.Global_active_power, bins=np.arange(0, 8, 0.5), sort=False) index = y.index fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.bar(index, y, width=0.5, color='r') ax.set_xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Frequency') ax.set_title('Global Active Power') pylab.show() # hpc[hpc['Global_active_power'] > 4]
def optimization_run_property_per_multistart( results: Union[Result, Sequence[Result]], opt_run_property: str, axes: Optional[matplotlib.axes.Axes] = None, size: Tuple[float, float] = (18.5, 10.5), start_indices: Optional[Union[int, Iterable[int]]] = None, colors: Optional[Union[List[float], List[List[float]]]] = None, legends: Optional[Union[str, List[str]]] = None, plot_type: str = 'line', ) -> matplotlib.axes.Axes: """ Plot stats for an optimization run property specified by opt_run_property. It is possible to plot a histogram or a line plot. In a line plot, on the x axis are the numbers of the multistarts, where the multistarts are ordered with respect to a function value. On the y axis of the line plot the value of the corresponding parameter for each multistart is displayed. Parameters ---------- opt_run_property: optimization run property to plot. One of the 'time', 'n_fval', 'n_grad', 'n_hess', 'n_res', 'n_sres' results: Optimization result obtained by 'optimize.py' or list of those axes: Axes object to use size: Figure size (width, height) in inches. Is only applied when no ax object is specified start_indices: List of integers specifying the multistarts to be plotted or int specifying up to which start index should be plotted colors: List of RGBA colors (one color per result in results), or single RGBA color. If not set and one result, clustering is done and colors are assigned automatically legends: Labels for line plots, one label per result object plot_type: Specifies plot type. Possible values: 'line', 'hist', 'both' Returns ------- ax: The plot axes. """ supported_properties = { 'time': 'Wall-clock time (seconds)', 'n_fval': 'Number of function evaluations', 'n_grad': 'Number of gradient evaluations', 'n_hess': 'Number of Hessian evaluations', 'n_res': 'Number of residuals evaluations', 'n_sres': 'Number of residual sensitivity evaluations', } if opt_run_property not in supported_properties: raise ValueError("Wrong value of opt_run_property. Only the following " "values are allowed: 'time', 'n_fval', 'n_grad', " "'n_hess', 'n_res', 'n_sres'") # parse input (results, colors, legends) = process_result_list(results, colors, legends) # axes if axes is None: ncols = 2 if plot_type == 'both' else 1 fig, axes = plt.subplots(1, ncols) fig.set_size_inches(*size) fig.suptitle( f'{supported_properties[opt_run_property]} per optimizer run') else: axes.set_title( f'{supported_properties[opt_run_property]} per optimizer run') # loop over results for j, result in enumerate(results): if plot_type == 'both': axes[0] = stats_lowlevel( result, opt_run_property, supported_properties[opt_run_property], axes[0], start_indices, colors[j], legends[j], ) axes[1] = stats_lowlevel( result, opt_run_property, supported_properties[opt_run_property], axes[1], start_indices, colors[j], legends[j], plot_type='hist', ) else: axes = stats_lowlevel( result, opt_run_property, supported_properties[opt_run_property], axes, start_indices, colors[j], legends[j], plot_type, ) if sum((legend is not None for legend in legends)) > 0: if plot_type == 'both': for ax in axes: ax.legend() else: axes.legend() return axes
# #### After 25 days there are dozens more bees present, and they tend to cluster around the queen and the newly born workers. Social behaviors are normal. # In[30]: t=25 #25 days, more bees! D=0.1 def u(x,y,t): return (1/(4*np.pi*D*t)*np.exp(-(x**2+y**2)/(4*D*t))) x=np.linspace(-7, 7, 100) y=np.linspace(-5, 5, 100) X, Y = np.meshgrid (x, y) Z=u(X,Y,t) figu=plt.figure() ax=plt.axes(projection='3d') ax.set_title("Concentration of thermal energy") ax.plot_surface(X,Y,Z,color='m') # # Thermal energy distribution in a mature colony under neonicotinoid exposure # # #### We're going to see a sparser distribution of bees in the center; there will be more individuals clustered at the edges of the space due to neonicotinoids' impact on bees' social behavior. The difference from normal colonies is even more pronounced in the evening. # In[49]: t=25 #days def f(x, y): return np.sin(np.sqrt(x ** 2 + y ** 2)) x = np.linspace(-7, 7, 30)
def create_bar_graph(data=[[[1, 2], [10, 20]]], semilog=False, add_bar_labels=True, title='Insert Fancy Title', add_legend=False, bar_colors=[], legend_labels=[]): import matplotlib.patches as mpatches from collections import deque if not bar_colors: bar_color_deque = deque([ '#1395ba', '#a2b86c', '#ebc844', '#f16c20', '#c02e1d', '#0d3c55', '#ecaa38', '#117899', '#d94e1f', '#5ca793', '#ef8b2c', '#0f5b78' ]) else: bar_color_deque = deque(bar_colors) width = 0.33 xs = data[0][0] legend_labels_queue = deque(legend_labels) handles = [] if len(data) > 1: width = 0.33 * 2 / len(data) #plot comparison from multiple archives all_unique_x = {} for series in data: for size in series[0]: all_unique_x[size] = True ind = np.arange(len(all_unique_x.keys())) rect_refs = [] fig, ax = plt.subplots() bar_shift = width / 2 #plot individual bars to allow for sparse data plots for series in data: if len(series) > 2: label = series[2] color = bar_color_deque.popleft() if legend_labels: legend_label = legend_labels_queue.popleft() else: legend_label = label handles.append(mpatches.Patch(color=color, label=legend_label)) index = 0 labeled_yet = False for ex in sorted(all_unique_x.keys()): for i in range(0, len(series[0])): if series[0][i] == ex: if 'label' in locals() and not labeled_yet: rects = ax.bar(index + bar_shift, series[1][i], width, color=color, label=label) labeled_yet = True else: rects = ax.bar(index + bar_shift, series[1][i], width, color=color) rect_refs.append(rects[0]) if add_bar_labels: bar_label(ax, rects, semilog) index += 1 bar_shift += width if semilog: ax.set_yscale('log') ax.set_xticks(ind + 0.59 - 0.045 * len(data)) if add_legend: plt.legend(handles=handles, loc=2) else: color = bar_color_deque.popleft() ys = data[0][1] ind = np.arange(len(xs)) fig, ax = plt.subplots() rects = ax.bar(ind + width, ys, color=color) ax.set_xticks(ind + width * 2) if semilog: ax.set_yscale('log') if add_bar_labels: bar_label(ax, rects, semilog) fig.set_size_inches(15, 8) ax.set_xticklabels(xs, rotation=0) ax.set_title(title) ax.set_xlabel("Object Size (Bytes)") ax.set_ylabel('MB/s') plt.show() plt.savefig('foo.png') return
import mglearn as ml import matplotlib.pyplot as plt import matplotlib.axes as ax from sklearn.neighbors import KNeighborsClassifier x,y = ml.datasets.make_forge() fig,axes = plt.subplots(1,3,figsize=(10,3)) for n_neighbors , ax in zip([1,3,9],axes): clf = KNeighborsClassifier(n_neighbors=n_neighbors).fit(x,y) ml.plots.plot_2d_separator(clf , x , fill=True , eps=0.5 , ax=ax , alpha=.4) ax.scatter(x[:,0] , x[:,1] , c=y , s=60 , cmap=ml.cm2) ax.set_title("%d neighbor(s) " % n_neighbors) plt.show()