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 redo_axes_ticks(self, axes:matplotlib.axes.Axes, x_len:int, y_len:int): downsample = self.w_downsample.value() x_stops = np.linspace(0, x_len, 6) x_stops_downsampled = x_stops / downsample axes.set_xticks(x_stops_downsampled) axes.set_xticklabels(["%d" % x for x in x_stops]) y_stops = np.linspace(0, y_len, 6)[::-1] y_stops_downsampled = y_stops / downsample axes.set_yticks(y_stops_downsampled) axes.set_yticklabels(["%d" % y for y in y_stops])
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 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')
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.drop(['Date', 'Time'], axis=1).set_index('DT') hpc = hpc['1/2/2007':'3/2/2007'].convert_objects(convert_numeric=True) hpc = hpc[0:2881] # create plotting variables x = pd.date_range('2/1/2007', '2/3/2007 00:00', freq='T') y = hpc['Global_active_power'] #plt.plot(y, color='k') fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(x, y, color='k') ax.set_xticklabels(['Thur', '', '', '', 'Fri', '', '', '', 'Sat']) ax.set_yticklabels(['0', '', '2', '', '4', '', '6']) #plt.xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Global Active Power (kilowatts)') #plt.title('Global Active Power') pylab.show()
domain_x = 20 domain_y = 20 iterations = 200 # Should not need to adjust anything below here domain = np.genfromtxt(domain_file, skip_header=2) pos_data = np.zeros(14) dom_x, dom_y = domain.shape for time in range(0, iterations): print(time) plt.figure() plt.title("Time = {0}".format(time)) ax = plt.gca() ax.set_xticks(np.arange(-.5, 20, 1)) ax.set_yticks(np.arange(-.5, 20, 1)) ax.set_xticklabels(np.arange(0, 20, 1)) ax.set_yticklabels(np.arange(0, 20, 1)) plt.imshow(domain, cmap=cm.jet, interpolation='nearest') for i in range(0, cores): for j in range(0, int(seekers / cores)): filename = "PositionalData/pos_procseeker{0}_Iter{1}.dat".format( 1000 * i + j, time) temp_plot = np.genfromtxt(filename) plt.plot(temp_plot[:, 0], temp_plot[:, 1], 'x') #plt.show() plt.savefig("PositionalData/Positions_{0}.png".format(time), dpi=200) plt.close()
import matplotlib.pyplot as plt import matplotlib.axes as ax from matplotlib.animation import FuncAnimation from random import uniform, choice import os speeds = [ 0.08, -0.08, 0.07, -0.07, 0.06, -0.06, 0.05, -0.05, 0.04, -0.04, 0, 0 ] # ---------------------------CREATE FIGURES/PLOTS------------------------------ # Create upper graph fig = plt.figure(figsize=(10, 8)) ax = plt.subplot(211) # (rows, columns, plot index) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xticks([]) ax.set_yticks([]) x_max = 10 y_max = 6 xy_min = 0 ax.set_xlim(right=x_max) ax.set_ylim(top=y_max) # Create bottom graph ax2 = plt.subplot(212) ax2.set_xlim(right=1000) ax2.set_ylim(top=70)
def _plot(self): self.figure.clear() self.canvas.draw() self.buttonSave.setEnabled(False) if self.pt is None and self.rectangle is None: return if self.parameter is None or self.coverage is None or self.dataset is None: return canvasLayers = [] try: allCoverageLayers = layers._layers[self.dataset][self.coverage] except KeyError: return for layerdef in allCoverageLayers: source = layerdef.source() time = parser.parse(layerdef.time()) try: layer = layerFromSource(source) canvasLayers.append((layerdef, time)) except WrongLayerSourceException: pass if not canvasLayers: return minDate = None maxDate = None minY = None maxY = None if self.filter: if self.filter[0] is not None: minDate = self.filter[0] if self.filter[1] is not None: maxDate = self.filter[1] minY = self.filter[2] or None maxY = self.filter[3] or None try: bands = allCoverageLayers[0].bands() if self.rectangle is None: self.data = {} startProgressBar("Retrieving plot data", len(canvasLayers)) for (i, (layerdef, time)) in enumerate(canvasLayers): if ((minDate is not None and time < minDate) or (maxDate is not None and time > maxDate)): continue start = timelib.time() layer = layerdef.layer() v = self.parameter.value(layer, self.pt, bands) end = timelib.time() logger.info( "Plot data for layer %i retrieved in %s seconds" % (i, str(end - start))) setProgressValue(i + 1) if v is not None: self.data[time] = [(v, (self.pt.x(), self.pt.y()))] closeProgressBar() if not self.data: return y = [v[0][0] for v in self.data.values()] ymin = min(y) ymax = max(y) else: self.data = {} startProgressBar("Retrieving plot data", len(canvasLayers)) for (i, (layerdef, time)) in enumerate(canvasLayers): if ((minDate is not None and time < minDate) or (maxDate is not None and time > maxDate)): continue start = timelib.time() layer = layerdef.layer() if not self.rectangle.intersects(layer.extent()): continue rectangle = self.rectangle.intersect(layer.extent()) xsteps = int(rectangle.width() / layer.rasterUnitsPerPixelX()) ysteps = int(rectangle.height() / layer.rasterUnitsPerPixelY()) filename = layerdef.layerFile(rectangle) roi = layers.getBandArrays(filename) end = timelib.time() logger.info( "ROI data for layer %i retrieved in %s seconds" % (i, str(end - start))) start = timelib.time() setProgressValue(i + 1) self.data[time] = [] for col in range(xsteps): x = rectangle.xMinimum( ) + col * layer.rasterUnitsPerPixelX() for row in range(ysteps): y = rectangle.yMinimum( ) + row * layer.rasterUnitsPerPixelY() pixel = QgsPoint(col, row) value = self.parameter.value(roi, pixel, bands) if value: self.data[time].append((value, (x, y))) end = timelib.time() logger.info( "Plot data computed from ROI data in %s seconds" % (str(end - start))) closeProgressBar() if not self.data: return y = [[v[0] for v in lis] for lis in self.data.values()] ymin = min([min(v) for v in y]) ymax = max([max(v) for v in y]) xmin = min(self.data.keys()) xmax = max(self.data.keys()) if self.filter is None: self.plotDataChanged.emit(xmin, xmax, ymin, ymax) self.dataToPlot = copy.deepcopy(self.data) if self.filter: for key, values in self.data.iteritems(): for v in values[::-1]: if ((minY is not None and v[0] < minY) or (maxY is not None and v[0] > maxY)): try: self.dataToPlot[key].remove(v) except: pass datesToRemove = [] for key, values in self.dataToPlot.iteritems(): if not values: datesToRemove.append(key) for d in datesToRemove: del self.dataToPlot[d] axes = self.figure.add_subplot(1, 1, 1) x = matplotlib.dates.date2num(self.dataToPlot.keys()) if self.rectangle is None: y = [v[0][0] for v in self.dataToPlot.values() if v] axes.scatter(self.dataToPlot.keys(), y) else: sortedKeys = sorted(self.dataToPlot.keys()) y = [[v[0] for v in self.dataToPlot[k]] for k in sortedKeys] axes.boxplot(y) axes.set_xticklabels( [str(d).split(" ")[0] for d in sortedKeys], rotation=70) self.figure.autofmt_xdate() except Exception, e: traceback.print_exc() closeProgressBar() return
for i in range(len(list_point_end_file)): if (list_point_end_file[i] >= cut_start) & (list_point_end_file[i] < cut_end): plt.axvline(list_point_end_file[i] - cut_start, color='black', linestyle='-', linewidth=0.1) cut_lable.append(labels[i]) cut_list_point.append(list_point_end_file[i] - cut_start) # print(labels[i]) # ax.set_xticks(list_point_end_file) # ax.set_xticklabels(labels,rotation=60) ax.set_xticks(cut_list_point) ax.set_xticklabels(cut_lable, rotation=60) fig = plt.gcf() fig.set_size_inches(18, 5.5) plt.ylabel('value') plt.xlabel('Time') # plt.show() window = [] list_mean = [] list_up_variance = [] list_low_variance = [] for data in stream_data: if len(window) >= max_size: window.pop(0) window.append(data) mean = sum(window) / len(window)
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=['Sub_metering_1', 'Sub_metering_2', 'Sub_metering_3', 'Date']) # hpc = hpc.drop(['Date', 'Time'], axis=1).set_index('DT') hpc = hpc['1/2/2007':'3/2/2007'].convert_objects(convert_numeric=True) hpc = hpc[0:2881] # create plotting variables x = pd.date_range('2/1/2007', '2/3/2007 00:00', freq='T') y1 = hpc.Sub_metering_1 y2 = hpc.Sub_metering_2 y3 = hpc.Sub_metering_3 fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(x, y1, color='k', label='Sub_metering_1') ax.plot(x, y2, color='r', label='Sub_metering_2') ax.plot(x, y3, color='b', label='Sub_metering_3') ax.legend(loc='best') ax.set_xticklabels(['Thur', '', '', '', 'Fri', '', '', '','Sat']) ax.set_yticklabels(['0', '', '10', '', '20', '', '30']) #plt.xlabel('Global Active Power (kilowatts)') ax.set_ylabel('Energy sub metering') #plt.title('Global Active Power') pylab.show()
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
plt.ylabel('Time of the Day') y = [y for y in range(6,144,6)] x = [x for x in range(0, global_count)] ax.set_yticks(y) ax.set_xticks(x) plt.xticks(rotation=50) for i in range(len(trip_IDs)): if i%5 != 0: trip_IDs[i]="" ax.set_xticklabels(trip_IDs) ax.set_yticklabels(ylabels) plt.tight_layout() plt.show() ''' #plt.subplot() pos = np.arange(len(xlabels_slots)) width = 1 ax = plt.axes() ax.set_xticks(pos + (width/2)) plt.xticks(rotation=50) ax.set_xticklabels(xlabels_slots) plt.bar(pos, frequencies[:23], width, color='r') plt.tight_layout() plt.gcf() plt.savefig('histogram' + file + '.png', bbox_inches='tight') #plt.show()
labels = [label.replace('20140927', '') for label in labels] stream_data = [] for test_file in test_files: dir = os.path.join(test_path, test_file) with open(dir) as txt_lines: list_point_end_file.append(len(stream_data)) for line in txt_lines: stream_data.append(int(line.replace('\n', ''))) ax = plt.subplot(111) plt.plot(stream_data) print(list_point_end_file) for i in range(len(list_point_end_file)): plt.axvline(list_point_end_file[i], color='black', linestyle='-',linewidth=0.1) ax.set_xticks(list_point_end_file) ax.set_xticklabels(labels,rotation=60) plt.ylabel('value') plt.xlabel('Time') plt.show() window_size = 6000 loop = int(len(stream_data)/window_size)+1 print(loop) start_point = 0 end_point = 0 print(len(stream_data)) change_points = [] for i in range(int(loop)): ax = plt.subplot(111) if(i == 0): start_point = 0
plt.close() with PdfPages('ImagenFantasma_x_tamaño.pdf') as pdf: #plt.figure(figsize=(7, 5)) labels = 'ASM', 'O3', 'O2', 'O0' barValues = [resASM[7],resC3[7],resC2[7],resC0[7]] x = [1,2,3,4] fig, ax = plt.subplots() rects1 = ax.bar(x, barValues,0.7, label='') plt.ylabel('') plt.xlabel("Implementaciones") plt.ylabel("Ciclos de clock") plt.title("Imagen Fantasma 1600x1200") ax.ticklabel_format(style='plain') ax.set_xticks(x) ax.set_xticklabels(labels) plt.grid(linestyle='-', linewidth=1, axis='y') pdf.savefig(bbox_inches='tight') plt.close() def calcularPorcentaje(asm, c): return int((asm*100)/c) for i in range(0,8): asm_vs_o3 = calcularPorcentaje(resASM[i], resC3[i]) asm_vs_o2 = calcularPorcentaje(resASM[i], resC2[i]) asm_vs_o0 = calcularPorcentaje(resASM[i], resC0[i]) print(" ") print("imagenFantasma_asm_vs_O0: " + str(asm_vs_o0) + '%') print("imagenFantasma_asm_vs_O2: " + str(asm_vs_o2) + '%')