def Plot(X,Y,Name,save=False,savename=None,title=None): x,y = np.hsplit(X,2) x = np.reshape(x,(41,41)) y = np.reshape(y,(41,41)) z = np.reshape(Y,(41,41)) fig = plt.figure(Name,figsize=(32,24)) ax = fig.gca(projection='3d') if(title != None): plt.title(title,fontsize=40) surf = ax.plot_surface(x, y, z, cmap=cm.coolwarm,linewidth=1, antialiased=True) fig.colorbar(surf, shrink=0.5, aspect=5,pad=-0.07) ax.view_init(azim=-120,elev = 70) ax.set_zlabel('\nY ',fontsize=50) ax.set_ylabel('\n$X_1$ ',fontsize=50) ax.set_xlabel('\n\n$X_0$',fontsize=50) if(save): pylab.get_current_fig_manager().window.showMaximized() ax.set_xlim3d([-2, 2]) ax.set_ylim3d([-2, 2]) ax.set_zlim3d([0, 1.5]) plt.savefig(savename,dpi=100,layout='tight_layout') plt.close(Name) return plt.show()
def on_click(event): tb = plt.get_current_fig_manager().toolbar if event.xdata is None: return if tb.mode != '': print 'Not in click mode - turn of pan or zoom' return if event.button == 1: classification = "good" elif event.button == 3: classification = "bad" else: return y = round(event.ydata) x = int(round(event.xdata)) i = np.searchsorted(bb_locs, x) left, right = bb_locs[i - 1], bb_locs[i] assert left < x < right vals = im_finger[y, left:right] if x < im_finger.shape[1] // 2: vals = vals[::-1] plt.figure() plt.plot(vals) plt.show() valstr = ','.join(["%0.02f" % (v) for v in vals]) f.write("%s,%s\n" % (classification, valstr))
def showimage(request, id): # matrix = np.array() result_document = ResultDocument.objects.filter(id=id)[0] result_document_path = os.path.join(settings.MEDIA_ROOT, result_document.file.name) with open(result_document_path, 'r') as file: text = file.read().splitlines() file.close() tmp_array = [] for line in text: line = re.sub("[\[\] ]+|,$|,]$", "", line) line = line.split(',') line = [float(z) for z in line] tmp_array.append(line) matrix = np.array(tmp_array) figure(figsize=(15, 10)) title(result_document.name) dendogram = dendrogram(matrix, truncate_mode="none") # Store image in a string buffer buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() # Send buffer in a http response the the browser with the mime type image/png set return HttpResponse(buffer.getvalue(), content_type="image/png")
def sleeptrack(request, current): user = get_object_or_404(User_Alarm, user_id=current) if request.method == 'GET': result = user.night_set.all() if ("application/json" in request.META.get("HTTP_ACCEPT")): result = json.loads(serializers.serialize('json', result)) return JsonResponse({"data": result}) elif True or ("image/png" in request.META.get("HTTP_ACCEPT")): x = [] y = [] for night in result: x.append(night.day_id) y.append(night.conversion()) plt.bar(x, y, width=0.5, color='blue') plt.xlabel('Day') plt.ylabel('Time') plt.title('Sleepdata') plt.xticks(range(len(x) + 1)) buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") plt.close() return HttpResponse(buffer.getvalue(), content_type='image/png') else: return HttpResponse(list(result))
def products(request): products = Product.objects.raw('SELECT * FROM firstapp_product') plot_x = [22, 23, 24, 25, 26, 27, 28] plot_y = [1223, 2633, 6765, 3553, 8765, 7654, 9876] # plt.plot(plot_x,plot_y) # response = plt.show() # Construct the graph # t = arange(0.0, 2.0, 0.01) # s = sin(2*pi*t) plt.plot(plot_x, plot_y) xlabel('time (s)') ylabel('voltage (mV)') title('About as simple as it gets, folks') grid(True) # Store image in a string buffer buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() # response = HttpResponse(buffer.getvalue(), content_type="image/png") # Send buffer in a http response the the browser with the mime type image/png set # return render(request,'firstapp/products.html',{'response':response }) return HttpResponse(buffer.getvalue(), content_type="image/png")
def scatter_plot(self): sm_value = self.sm_value ob_value = self.ob_value figure = plt.figure(facecolor='white') subplot = figure.add_subplot(111) index_non_nan = np.isfinite(sm_value) & np.isfinite(ob_value) fit = np.polyfit(sm_value[index_non_nan],ob_value[index_non_nan],deg = 1) fx = np.poly1d(fit) subplot.scatter(sm_value,ob_value) subplot.plot(sm_value, fx(sm_value), color = 'r') grid(True) formatter = DateFormatter('%Y/%m') subplot.set_xlabel("Simulation") subplot.set_ylabel("Observation") subplot.grid() # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def plot_results(times_A, times_B, signal_A, signal_B, convoluted_signals, time_offset, block=True): fig = plt.figure() title_position = 1.05 matplotlib.rcParams.update({'font.size': 20}) # fig.suptitle("Time Alignment", fontsize='24') a1 = plt.subplot(1, 3, 1) a1.get_xaxis().get_major_formatter().set_useOffset(False) plt.ylabel('angular velocity norm [rad]') plt.xlabel('time [s]') a1.set_title( "Before Time Alignment", y=title_position) plt.hold("on") min_time = min(np.amin(times_A), np.amin(times_B)) times_A_zeroed = times_A - min_time times_B_zeroed = times_B - min_time plt.plot(times_A_zeroed, signal_A, c='r') plt.plot(times_B_zeroed, signal_B, c='b') times_A_shifted = times_A + time_offset a3 = plt.subplot(1, 3, 2) a3.get_xaxis().get_major_formatter().set_useOffset(False) plt.ylabel('correlation') plt.xlabel('sample idx offset') a3.set_title( "Correlation Result \n[Ideally has a single dominant peak.]", y=title_position) plt.hold("on") plt.plot(np.arange(-len(signal_A) + 1, len(signal_B)), convoluted_signals) a2 = plt.subplot(1, 3, 3) a2.get_xaxis().get_major_formatter().set_useOffset(False) plt.ylabel('angular velocity norm [rad]') plt.xlabel('time [s]') a2.set_title( "After Time Alignment", y=title_position) plt.hold("on") min_time = min(np.amin(times_A_shifted), np.amin(times_B)) times_A_shifted_zeroed = times_A_shifted - min_time times_B_zeroed = times_B - min_time plt.plot(times_A_shifted_zeroed, signal_A, c='r') plt.plot(times_B_zeroed, signal_B, c='b') plt.subplots_adjust(left=0.04, right=0.99, top=0.8, bottom=0.15) if plt.get_backend() == 'TkAgg': mng = plt.get_current_fig_manager() max_size = mng.window.maxsize() max_size = (max_size[0], max_size[1] * 0.45) mng.resize(*max_size) plt.show(block=block)
def showimage(request): from django.http import HttpResponse from matplotlib import pylab import PIL, PIL.Image from django.utils.six import StringIO from numpy import arange, sin, pi from matplotlib.pyplot import plot from matplotlib.pyplot import xlabel from matplotlib.pyplot import ylabel from matplotlib.pyplot import title from matplotlib.pyplot import grid # Construct the graph t = arange(0.0, 2.0, 0.01) s = sin(2 * pi * t) plot(t, s, linewidth=1.0) xlabel('time (s)') ylabel('voltage (mV)') title('About as simple as it gets, folks') grid(True) # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.cose() # Send buffer in a http response the the browser with the mime type image/png set return HttpResponse(buffer.getvalue(), mimetype="image/png")
def plot(request): plot_id = request.GET.get('id') algo_list = Algo.objects.all() if plot_id: current_algo = Algo.objects.get(id=plot_id) positions_y = current_algo.positions positions_x = [i for i in range(1, len(positions_y) + 1)] pnl_y = current_algo.daily_pnl pnl_x = [i for i in range(1, len(pnl_y) + 1)] fig = pylab.figure() fig.add_subplot(2, 2, 1) pylab.plot(positions_x, positions_y) fig.add_subplot(2, 2, 2) pylab.plot(pnl_x, pnl_y) buffer = BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png") return render(request, 'index.html', {'algo_list': algo_list, 'plt': plt})
def plot_graph(file_name: str, col: str = "", show: bool = False) -> None: """ Formats the plot, saves (and optionally displays) it in a nice format. Arguments: file_name {str} -- the file name of the plot to be saved Keyword Arguments: col {str} -- the parameter of interest (default: {""}) show {bool} -- display the plot on the screen (default: {False}) """ plt.grid() manager = plt.get_current_fig_manager() manager.window.showMaximized() fig = plt.gcf() fig.set_size_inches(11, 8.5) # standard A4 sheet size if col: file_name = f"{col}/" + file_name + f"-{col}" path = os.path.join(FIGURES, file_name + ".png") plt.savefig(path, dpi=500) if show: plt.show() plt.close()
def stats(request): s = Sightings.objects.all().values() df=pd.DataFrame(s) df2=pd.read_csv('file.csv') df2.groupby('primary_fur_color').count()['x'] explode=(0,0,0) labels='Black','Cinnamon','Gray' s=df2.groupby('primary_fur_color').count()['x'].sum() x1=(df2.groupby('primary_fur_color').count()['x'][0])/s*100 x2=(df2.groupby('primary_fur_color').count()['x'][1])/s*100 x3=(df2.groupby('primary_fur_color').count()['x'][2])/s*100 sizes=[x1,x2,x3] lst=[df2.groupby('shift').count()['x'][f] for f in range(2)] x=['AM','PM'] fig, (ax1, ax2) = plt.subplots(2) ax1.pie(sizes, explode=explode, labels=labels) ax2.bar(x, height=lst) ax2.title.set_text('Variations in shift sightings') ax2.set_xlabel('Shift') ax2.set_ylabel('Frequency of Sightings') buffer = BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer,"PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type= "image/png") pass
def outlierDetectionPlot(self,filteredData,variable="",unit=""): outlierDataPD = filteredData[filteredData['outlier'] == True] # filteredData[filteredData['outlier'] == True] = np.nan figure = plt.figure(facecolor='white') subplot = figure.add_subplot(111) orginalData, = subplot.plot(filteredData.index.values,filteredData[variable].values,color = 'b') outlierData = subplot.scatter(outlierDataPD.index.values,outlierDataPD[variable].values,color = 'r') subplot.set_ylabel(variable +"("+unit+")") subplot.legend([outlierData],["Outliers"]) subplot.grid() grid(True) subplot.xaxis.set_major_locator(MaxNLocator(8)) # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def multipleBoxPlot(DF, variable = "", unit = ""): DF = DF.dropna() meds = DF.median() meds.sort(ascending=False) DF = DF[meds.index] columns = DF.columns figure = plt.figure(figsize=(20, 15)) figure.patch.set_facecolor('white') for column in columns: plt.boxplot(DF[columns].values) xticks(range(1,len(columns) + 1),columns, rotation=90) if variable != "" and unit != "": ylabel(variable + " (" + unit + ")") else: pass # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def studio_data(request): df = pd.read_excel('C:/data_boy/tickets/studiodata.xlsx') tickets = df['# of Tickets Bought'] studio = df['Studio'] colors = [ '#b1ffb0', '#f38630', '#a495bf', '#f4eac1', '#13e36a', '#ff9944', '#ab7694', '#89ec6b' ] fig1, ax1 = plt.subplots() ax1.pie(tickets, labels=studio, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') plt.title("Breakdown by major studios:") buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png")
def _fourier_series_helper(form): c_k = eval(form.cleaned_data['c_k']) n = float(form.cleaned_data['series_len']) l = float(form.cleaned_data['lower_bound']) u = float(form.cleaned_data['upper_bound']) f = float(form.cleaned_data['fundamental']) if form.cleaned_data['method'] != "all": # n = 2 * n if form.cleaned_data['method'] == "even": c_k = lambda k: eval(form.cleaned_data['c_k'])(k) * (1 - (k % 2)) else: c_k = lambda k: eval(form.cleaned_data['c_k'])(k) * (k % 2) kl = -(n // 2) x = linspace(l, u, form.cleaned_data['points']) k = arange(kl, kl + n) ck = c_k(k) ck[(isinf(ck)) | (isnan(ck))] = 0 s = matmul(ck, exp(2.0j * pi * outer(k, x) * f)) print(s) plt.figure() plt.plot(x, real(s)) buffer = BytesIO() canvas = plt.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") return buffer
def plot_angular_velocities(title, angular_velocities, angular_velocities_filtered, block=True): fig = plt.figure() title_position = 1.05 fig.suptitle(title, fontsize='24') a1 = plt.subplot(1, 2, 1) a1.set_title( "Angular Velocities Before Filtering \nvx [red], vy [green], vz [blue]", y=title_position) plt.plot(angular_velocities[:, 0], c='r') plt.plot(angular_velocities[:, 1], c='g') plt.plot(angular_velocities[:, 2], c='b') a2 = plt.subplot(1, 2, 2) a2.set_title( "Angular Velocities After Filtering \nvx [red], vy [green], vz [blue]", y=title_position) plt.plot(angular_velocities_filtered[:, 0], c='r') plt.plot(angular_velocities_filtered[:, 1], c='g') plt.plot(angular_velocities_filtered[:, 2], c='b') plt.subplots_adjust(left=0.025, right=0.975, top=0.8, bottom=0.05) if plt.get_backend() == 'TkAgg': mng = plt.get_current_fig_manager() max_size = mng.window.maxsize() max_size = (max_size[0], max_size[1] * 0.45) mng.resize(*max_size) plt.show(block=block)
def plot_training_curves( folders, metric_name='mse', sets=['valid', 'train'], print_set_in_legend=True): fig = plt.figure(num=None, figsize=(9, 5), dpi=80, facecolor='w', edgecolor='k') plt.get_current_fig_manager().window.raise_() cmap = plt.get_cmap('prism') # colors = [cmap(i) for i in np.linspace(0, 1, 10*len(FOLDERS))] colors = ['b', 'g', 'r', 'm', 'y', 'k', 'c'] lines = ["-","--","-.",":"] colorcyler = cycle(colors) for (folder, name) in folders: c = next(colorcyler) for i, set in enumerate(sets): f = os.path.join(folder, 'metric_saver_' + set + '.pkl') data = cPickle.load(open(f, 'r')) ls_metric_names = data['names'] if metric_name in ls_metric_names: id_feature = ls_metric_names.index(metric_name) else: continue if not data['history'].any(): continue feature = data['history'][:, id_feature] if print_set_in_legend: label = set + '_' + name else: label = name plt.plot(data['iterations'], feature, lines[i], color=c, label=label) plt.xlabel('Number of minibatches') plt.ylabel(metric_name) plt.legend(loc='best', frameon=False, prop={'size':13}) plt.title('Validation ' + metric_name +' through training') plt.grid(True, alpha=0.5) # fig.legend(legend_curves, legend_names, 'lower center', ncol=2, frameon=False, # prop={'size':12}) # plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.6, hspace=3) plt.show() # plt.savefig('comparison_attention.pdf')
def showImage(self): if self.transfer_images == []: self.image_reconstruction() size = 16 plt.subplot(4, 15, 1) plt.ylabel("origin", fontsize=size) plt.subplot(4, 15, 16) plt.ylabel("reconstruction", fontsize=size) plt.subplot(4, 15, 31) plt.ylabel("origin", fontsize=size) plt.subplot(4, 15, 46) plt.ylabel("reconstruction", fontsize=size) for i in range(15): plt.subplot(4, 15, i + 1) plt.xticks([]) plt.yticks([]) plt.imshow(self.origin_images[i]) plt.subplot(4, 15, i + 16) plt.xticks([]) plt.yticks([]) plt.imshow( np.clip(self.transfer_images[i], 0, 255).astype(np.uint8)) for i in range(15, 30): plt.subplot(4, 15, i + 16) plt.xticks([]) plt.yticks([]) plt.imshow(self.origin_images[i]) plt.subplot(4, 15, i + 31) plt.xticks([]) plt.yticks([]) plt.imshow( np.clip(self.transfer_images[i], 0, 255).astype(np.uint8)) plt.get_current_fig_manager().window.showMaximized() plt.interactive(True) plt.show()
def get(self, request, pk): customer = get_object_or_404(Customer, pk=pk) # customers = Customer.objects.filter(created_date__lte=timezone.now()) investments = Investment.objects.filter(customer=pk) stocks = Stock.objects.filter(customer=pk) sum_recent_value = 0 sum_acquired_value = 0 for investment in investments: sum_recent_value += investment.recent_value sum_acquired_value += investment.acquired_value overall_investment_results = round(sum_recent_value - sum_acquired_value) # Initialize the value of the stocks sum_current_stocks_value = 0 sum_of_initial_stock_value = 0 # Loop through each stock and add the value to the total for stock in stocks: sum_current_stocks_value += stock.current_stock_value() sum_of_initial_stock_value += stock.initial_stock_value() results = round(sum_current_stocks_value - float(sum_of_initial_stock_value)) # Construct the graph inv_type = ['Stocks', 'Non-Stock'] value = ['Initial', 'Current'] invest_type = ['Stocks', 'Non-Stock'] inv_value = [sum_of_initial_stock_value, sum_acquired_value] cur_value = [sum_current_stocks_value, sum_recent_value] plt.bar([1, 2.7], inv_value, width=0.35, color='blue') plt.bar([1.35, 3.05], cur_value, width=0.35, color='red') plt.bar(4.4, results, width=0.35, color='green') plt.bar(4.75, overall_investment_results, width=0.35, color='yellow') plt.xticks([1.175, 2.875, 4.575], ['Stocks', 'Non-Stock', 'Net Return']) plt.legend(['Initial', 'Current', 'Stocks', 'Non-Stock'], loc=1) ylabel('Value (USD)') title('Overall portfolio performance') grid(False) # Store image in a string buffer buffer = BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() # Send buffer in a http response the the browser with the mime type image/png set return HttpResponse(buffer.getvalue(), content_type="image/png")
def showActivateWindow(): """ plt.show()してもウィンドウが前面に出ないため 出るようにする """ cfm = plt.get_current_fig_manager() cfm.window.activateWindow() cfm.window.raise_() plt.show()
def viewgraph(request): if request.POST: global csv_name, csv_data, display_data data = request.POST.copy() column_names = list(csv_data.columns.values) x_axis = column_names[int(data.get('xaxis')) - 1] y_axis = column_names[int(data.get('yaxis')) - 1] unique_column = "" if (data.get('unique')): unique_column = column_names[int(data.get('unique')) - 1] # plt.figure(figsize=(5, 5)) figure(figsize=(6, 6)) if (unique_column): unique_data_columns = pd.unique(csv_data[unique_column]) for unique_data_column in unique_data_columns: ix = getattr(csv_data, unique_column) == unique_data_column x, y = csv_data[x_axis][ix], csv_data[y_axis][ix] plot(x, y, ".", label=unique_data_column) legend() #plt.plot(x, y, ".", label=unique_data_column) else: x, y = csv_data[x_axis], csv_data[y_axis] #plt.plot(x, y, ".") plot(x, y, ".") xlabel(x_axis) ylabel(y_axis) # plt.xlabel(x_axis) # plt.ylabel(y_axis) # plt.legend() # x=csv_data[x_axis][ix] # y=csv_data[y_axis][ix] # plot(x,y) # # xlabel(x_axis) # ylabel(y_axis) # title(x_axis+' vs '+y_axis) # legend() #grid(true) buffer = BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) #pilImage = pilImage.decode("utf-8") pilImage.save(buffer, "PNG") return HttpResponse(buffer.getvalue(), content_type="image/png") #plt.show() context = { 'xaxis': xaxis, 'yaxis': yaxis, 'unique': unique, }
def in_concentration_graph(request): db = [6.0584, 5.65325] segregationCoefficient = float(request.GET.get('sc')) concentration = float(request.GET.get('c')) aWellAlloy = db[int(request.GET.get('wa'))] wellLength = float(request.GET.get('wl')) aRightBarrierAlloy = db[int(request.GET.get('rba'))] rightBarrierLength = float(request.GET.get('rbl')) latticeParam = aWellAlloy * concentration + aRightBarrierAlloy * (1 - concentration) wellMonoLayers = int((2 * wellLength) // latticeParam) rightBarrierMonoLayers = int((2 * rightBarrierLength) // aRightBarrierAlloy) concentrationInsideWell = lambda n: concentration * (1 - segregationCoefficient ** n) concentrationOutsideWell = lambda n: concentration * (1 - segregationCoefficient ** n) * (segregationCoefficient ** (n - wellMonoLayers)) gTitle = '' yTitle = 'In Concentration (%)' # Get current size fig_size = rcParams["figure.figsize"] # Set figure width to 12 and height to 9 fig_size[0] = 12 fig_size[1] = 6 rcParams["figure.figsize"] = fig_size f, (ax1, ax2) = subplots(1, 2, sharey=True) layers = [l for l in xrange(1, wellMonoLayers + 1)] wellPoints = [concentrationInsideWell(n) for n in xrange(1, wellMonoLayers + 1)] yTitle = "Energy (eV)" gTitle = "In Concentration Inside Well" ax1.step(layers, wellPoints, color='green', marker='', linestyle='solid') ax1.set_title(gTitle) ax1.set_xlabel("Layer") ax1.set_ylabel(yTitle) layers = [l for l in xrange(wellMonoLayers + 1, rightBarrierMonoLayers + 1)] wellPoints = [concentrationOutsideWell(n) for n in xrange(wellMonoLayers + 1, rightBarrierMonoLayers + 1)] gTitle = "In Concentration Outside Well" ax2.step(layers, wellPoints, color='green', marker='', linestyle='solid') ax2.set_title(gTitle) ax2.set_xlabel("Layer") ax2.set_ylabel(yTitle) buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png")
def screen_cut_and_get_point(): screen_img = screen_capture() pylab.figure(1, tight_layout=True) pylab.axis('off') pylab.imshow(screen_img) mng = pylab.get_current_fig_manager() mng.window.showMaximized() mng.set_window_title('请用鼠标点击希望模拟鼠标点击的区域') point = pylab.ginput(1)[0] pylab.close() return point
def plot_init(data): """Initialize plot. Args: data: team matrix """ # Set figure style sns.set_style("dark") # Create subplot grid fig = gridspec.GridSpec(2, 1) # Create subplots axarr = [plt.subplot(fig[0, 0]), plt.subplot(fig[1, 0])] # Plot data img = axarr[0].imshow(data, interpolation='nearest', cmap=plt.cm.ocean, extent=(0.5, np.shape(data)[0] + 0.5, 0.5, np.shape(data)[1] + 0.5)) # Display round plt.title("Current Round:" + str(0)) # Set labels axarr[0].set_ylabel("Give") axarr[0].set_xlabel("Accept") axarr[0].set_title("Distribution of Teams") # Plot average deal data axarr[1].plot(avg_deal_data) # Set labels axarr[1].set_xlim(0, rounds) axarr[1].set_ylabel("Average Cash per Deal") axarr[1].set_xlabel("Round Number") # Create colorbar for strategy distribution plt.colorbar(img, ax=axarr[0], label="Prevalence vs. Uniform") # Interactive mode plt.ion() # Changed this to use 'normal' instead of 'zoomed' since it didn't work on # my system mng = plt.get_current_fig_manager() mng.window.state('normal') # Display everything plt.show() return fig, axarr
def plot_all_line(self): data = [] label = [] for each_line in Line_list: data.append([ Line_list[each_line].CA_Current_G, Line_list[each_line].CA_Opti_G, Line_list[each_line].CA_Audit_G ]) label.append(Line_list[each_line].name) pylab.xlabel("Lignes") pylab.ylabel("Chiffre d'Affaires") pylab.title("Chiffre d'affaires par ligne") dim = len(data[0]) w = 0.75 dimw = w / dim color = ['r', 'g', 'y'] titre = ['CA actuelle', 'CA optimal', 'CA audit'] x = pylab.arange(len(data)) for i in range(len(data[0])): y = [d[i] for d in data] pylab.bar(x + i * dimw, y, dimw, bottom=0.001, color=color[i % 3], label=titre[i % 3]) pylab.legend() pylab.gca().set_xticks(x + w / 2) pylab.gca().set_xticklabels(label, rotation=90) pylab.subplots_adjust(bottom=0.1, top=0.96, right=0.98, left=0.05) major_formatter = pylab.FormatStrFormatter('%2.0f') pylab.gca().yaxis.set_major_formatter(major_formatter) pylab.get_current_fig_manager().window.showMaximized() pylab.show()
def graph(request): from matplotlib import pylab import numpy as np import matplotlib.pyplot as plt x1 = np.linspace(0.0, 5.0) x2 = np.linspace(0.0, 2.0) x3 = np.linspace(2.0, 4.0) x4 = np.linspace(0.0, 7.0) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) y2 = np.cos(2 * np.pi * x2) y3 = np.cos(2 * np.pi * x2) y4 = np.cos(2 * np.pi * x2) plt.subplot(2, 2, 1) plt.plot(x1, y1, 'yo-',) plt.title('Temperature') plt.ylabel('Celcius') plt.subplot(2, 2, 2) plt.plot(x3, y3, 'yo-') plt.title('Druck') plt.ylabel('Bar') plt.subplot(2, 2, 4) plt.plot(x2, y2, 'r.-') plt.title('4te Variable') plt.ylabel('unknown') plt.subplot(2, 2, 3) plt.plot(x3, y3, 'yo-') plt.title('Feuchtigkeit') plt.ylabel('Digits') buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer,"PNG") pylab.close() return HttpResponse(buffer.getvalue(), mimetype = "image/png")
def _fourier_series_sweep(form): c_k = eval(form.cleaned_data['c_k']) l = float(form.cleaned_data['lower_bound']) u = float(form.cleaned_data['upper_bound']) f = float(form.cleaned_data['fundamental']) if form.cleaned_data["custom_sweep"]: all_k = array(list(map(int, form.cleaned_data["k_terms"].split(",")))) else: kstart = int(form.cleaned_data['k_start']) kend = int(form.cleaned_data['k_end']) kstep = int(form.cleaned_data['k_step']) all_k = arange(kstart, kend + 1, kstep) if form.cleaned_data['method'] != "all": if form.cleaned_data['method'] == "even": c_k = lambda k: eval(form.cleaned_data['c_k'])(k) * (1 - (k % 2)) else: c_k = lambda k: eval(form.cleaned_data['c_k'])(k) * (k % 2) use_labels = all_k if all_k.shape[0] > 5: use_labels = all_k[::int(all_k.shape[0] / 5)] plt.figure() x = linspace(l, u, form.cleaned_data['points']) for n in all_k: kl = -(n // 2) k = arange(kl, kl + n) ck = c_k(k) ck[(isinf(ck)) | (isnan(ck))] = 0 s = matmul(ck, exp(2.0j * pi * outer(k, x) * f)) if n in use_labels: plt.plot(x, real(s), label=f"{n} terms") else: plt.plot(x, real(s), label=None) plt.legend() plt.grid() buffer = BytesIO() canvas = plt.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") return buffer
def residual_analysis(self): dropnan_DF = self.dropnan_DF model = sm.ols(formula='ob_value ~ sm_value', data=dropnan_DF) fitted = model.fit() fittedvalues = np.array(fitted.fittedvalues) residual = fittedvalues - np.array(dropnan_DF.ob_value) norm_residual = fitted.resid_pearson ### figure = plt.figure(facecolor='white') subplot1 = figure.add_subplot(2,2,1) subplot1.scatter(fittedvalues,residual) subplot1.set_xlabel("Fitted values") subplot1.set_ylabel("Residuals") subplot1.set_title("Residuals vs Fitted") subplot2 = figure.add_subplot(2,2,2) probplot(norm_residual,plot=subplot2) subplot2.set_title("Normal Q-Q") subplot2.set_ylabel("Standardized residuals") subplot2.set_xlabel("Theoretical Quantiles") subplot3 = figure.add_subplot(2,2,3) subplot3.scatter(fittedvalues,np.sqrt(np.abs(residual))) subplot3.set_title("Scale-Location") subplot3.set_ylabel(r'$\sqrt{\mathrm{|Standardized\/residuals|}}$') subplot3.set_xlabel("Fitted values") subplot4 = figure.add_subplot(2,2,4) norm_residual = (np.matrix(norm_residual)).T H = norm_residual*(norm_residual.T*norm_residual).I*norm_residual.T h = H.diagonal() subplot4.scatter(np.array(h),np.array(norm_residual.T)) subplot4.set_title("Residuals vs Leverage") subplot4.set_ylabel("Standardized residuals") subplot4.set_xlabel("Leverage") subplot4.xaxis.set_major_locator(MaxNLocator(6)) figure.tight_layout() # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def draw_mock_graph(): '''draw the toe energy per meter graph. ''' plt.plot([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 4, 5, 6, 7, 10, 15, 15, 15], 'ro') plt.axis([0, 10, 0, 20]) canvas = pylab.get_current_fig_manager().canvas canvas.draw() pil_image = Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pylab.close() return pil_image
def fit_pressures(target_sensor): conn = psycopg2.connect("dbname=will user=levlab host=levlabserver2.stanford.edu") cur = conn.cursor() sensor_query = '''SELECT {0}.name FROM {0} WHERE {0}.fault=FALSE and {0}.unit='Torr';'''.format(GAUGE_TABLE) cur.execute(sensor_query) sensors = cur.fetchall() databysensors = dict() notesbysensors = dict() for sensor in sensors: sensorname = sensor[0] data_query = '''SELECT {0}.time, {0}.value FROM {0}, {1} WHERE {0}.value > 0 and {0}.id = {1}.id and {1}.name = %s and {1}.unit='Torr' and {0}.time > %s;'''.format(PRESSURES_TABLE, GAUGE_TABLE) annotate_query = '''SELECT {0}.note, {0}.time, {0}.pressure FROM {0}, {1} WHERE {1}.name = %s and {0}.sensorid={1}.id'''.format(ANNOTATIONS_TABLE, GAUGE_TABLE) cur.execute(data_query, (sensorname, STARTDATETIME,)) databysensors[sensorname]=cur.fetchall() cur.execute(annotate_query, (sensorname,)) notesbysensors[sensorname]=cur.fetchall() cur.close() conn.close() time = [data[0] for data in databysensors[target_sensor]] time_secs = np.array([(t - STARTDATETIME).total_seconds() for t in time]) value = np.array([float(data[1]) for data in databysensors[target_sensor]]) p0 = np.array([P_FINAL, value[0] - P_FINAL, tau_guess]) popt, _ = optimize.curve_fit(exp_func, time_secs, value, p0) print popt fit_result = [exp_func(t, *popt) for t in time_secs] if P_FINAL > popt[0]: est_pumpdown = STARTDATETIME + datetime.timedelta(seconds = popt[2] * np.log(popt[1] / (P_FINAL - popt[0]))) print est_pumpdown else: print 'Desired pressure is unreachable.' one_wk_from_now_secs = ((datetime.datetime.now() - STARTDATETIME) + datetime.timedelta(weeks=1)).total_seconds() print 'Pressure in one week is: %e'%(exp_func(one_wk_from_now_secs, *popt)) fig = plt.figure(figsize=(12,6)) ax1 = fig.add_subplot(111) # ax1.set_yscale('log') ax1.plot_date(time, value,'-', label = sensor[0]) ax1.plot_date(time, fit_result, '-', label='Fit Result') ax1.fmt_xdate = pltdates.DateFormatter('%H%M') ax1.legend(loc = 'lower left') ax1.set_xlabel('Time') ax1.set_ylabel('Pressure / Torr') fig.autofmt_xdate() wm = plt.get_current_fig_manager() wm.window.wm_geometry("1920x1080+50+50") plt.show()
def plot_init(data): """Initialize plot. Args: data: team matrix """ # Set figure style sns.set_style("dark") # Create subplot grid fig = gridspec.GridSpec(2, 1) # Create subplots axarr = [plt.subplot(fig[0, 0]), plt.subplot(fig[1, 0])] # Plot data img = axarr[0].imshow(data, interpolation = 'nearest', cmap = plt.cm.ocean, extent = (0.5, np.shape(data)[0] + 0.5, 0.5, np.shape(data)[1] + 0.5)) # Display round plt.title("Current Round:" + str(0)) # Set labels axarr[0].set_ylabel("Give") axarr[0].set_xlabel("Accept") axarr[0].set_title("Distribution of Teams") # Plot average deal data axarr[1].plot(avg_deal_data) # Set labels axarr[1].set_xlim(0,rounds) axarr[1].set_ylabel("Average Cash per Deal") axarr[1].set_xlabel("Round Number") # Create colorbar for strategy distribution plt.colorbar(img, ax=axarr[0], label= "Prevalence vs. Uniform") # Interactive mode plt.ion() # Changed this to use 'normal' instead of 'zoomed' since it didn't work on # my system mng = plt.get_current_fig_manager() mng.window.state('normal') # Display everything plt.show() return fig, axarr
def history(request): ''' Creates a matplotlib line chart of the variant history and gives view. Returns a template of the home view ''' varHistory = Dspclinva.objects.values_list('date_created') date_list = [] for items in varHistory: date_list.append(items[0]) sortDateList = sort(date_list) dates = matplotlib.dates.date2num(sortDateList) counts = defaultdict(int) for item in dates: counts[item] += 1 allDates = [] allValues = [] for key, value in counts.iteritems(): allDates.append(key) allValues.append(value) addedValues = [] for index, elem in enumerate(allValues): if index == 0: temp = elem addedValues.append(temp) else: temp += elem addedValues.append(temp) sortDates = sort(allDates) x = sortDates y = addedValues years = mdates.YearLocator() # every year months = mdates.MonthLocator() # every month yearsFmt = mdates.DateFormatter('%Y') fig, ax = plt.subplots() ax.plot(x,y) ax.xaxis.set_major_locator(years) ax.xaxis.set_major_formatter(yearsFmt) ax.xaxis.set_minor_locator(months) fig.autofmt_xdate() buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png")
def alldata(request): sb.set_style("ticks") # sb.pairplot(df, hue='Region', diag_kind="kde", kind="scatter", palette="husl", bw=1.5) sb.pairplot(df) buffer = BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png")
def update_plots(self, atoms): """Update the coverage and TOF plots.""" # fetch data piggy-backed on atoms object new_time = atoms.kmc_time occupations = atoms.occupation.sum(axis=1) / lattice.spuck tof_data = atoms.tof_data # store locally while len(self.times) > getattr(settings, 'hist_length', 30): self.tof_hist.pop(0) self.times.pop(0) self.occupation_hist.pop(0) self.times.append(atoms.kmc_time) self.tof_hist.append(tof_data) self.occupation_hist.append(occupations) # plot TOFs for i, tof_plot in enumerate(self.tof_plots): tof_plot.set_xdata(self.times) tof_plot.set_ydata([tof[i] for tof in self.tof_hist]) self.tof_diagram.set_xlim(self.times[0], self.times[-1]) self.tof_diagram.set_ylim(1e-3, 10 * max([tof[i] for tof in self.tof_hist])) # plot occupation for i, occupation_plot in enumerate(self.occupation_plots): occupation_plot.set_xdata(self.times) occupation_plot.set_ydata( [occ[i] for occ in self.occupation_hist]) max_occ = max(occ[i] for occ in self.occupation_hist) self.occupation_diagram.set_ylim([0, max(1, max_occ)]) self.occupation_diagram.set_xlim([self.times[0], self.times[-1]]) self.data_plot.canvas.draw_idle() manager = plt.get_current_fig_manager() if hasattr(manager, 'toolbar'): toolbar = manager.toolbar if hasattr(toolbar, 'set_visible'): toolbar.set_visible(False) plt.show() # [:] is necessary so that it copies the # values and doesn't reinitialize the pointer self.time = new_time return False
def graph_in_endcode64(DF,variable="",unit="", title = "", linear_regression = False): DateTime = pandas.to_datetime(DF.index.values) data = np.array(DF.values) figure = plt.figure(facecolor='white') subplot = figure.add_subplot(111) # Construct the graph subplot.plot(DateTime, data, linewidth=1.0) if variable != "" and unit != "": subplot.set_xlabel('DateTime') subplot.set_ylabel(variable + " (" + unit + ")") else: pass if title != "": subplot.set_title(title) if linear_regression == True: index_non_nan = np.isfinite(data) x = np.array(mpl.dates.date2num(list(DateTime))) z = np.polyfit(x[index_non_nan],data[index_non_nan],1) p = np.poly1d(z) subplot.plot(DateTime,p(x),'r') else: pass formatter = DateFormatter('%m/%Y') subplot.grid(True) subplot.xaxis.set_major_formatter(formatter) subplot.xaxis.set_major_locator(MaxNLocator(8)) # figure.autofmt_xdate() # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def graph(request): x=[1,2,3,4,5,6] y=[5,2,6,8,2,7] plot(x,y,linewidth=2) xlabel('x axis') ylabel('y axis') title('sample graph') grid(True) buffer=StringIO.StringIO() canvas=pylab.get_current_fig_manager().canvas canvas.draw() graphIMG=PIL.Image.fromstring('RGB',canvas.get_width_height(),canvas.tostring_rgb()) graphIMG.save(buffer,'PNG') pylab.close() return HttpResponse(buffer.getvalue(),content_type='image/png')
def update_plots(self, atoms): """Update the coverage and TOF plots.""" # fetch data piggy-backed on atoms object new_time = atoms.kmc_time occupations = atoms.occupation.sum(axis=1) / lattice.spuck tof_data = atoms.tof_data # store locally while len(self.times) > getattr(settings, 'hist_length', 30): self.tof_hist.pop(0) self.times.pop(0) self.occupation_hist.pop(0) self.times.append(atoms.kmc_time) self.tof_hist.append(tof_data) self.occupation_hist.append(occupations) # plot TOFs for i, tof_plot in enumerate(self.tof_plots): tof_plot.set_xdata(self.times) tof_plot.set_ydata([tof[i] for tof in self.tof_hist]) self.tof_diagram.set_xlim(self.times[0], self.times[-1]) self.tof_diagram.set_ylim( 1e-3, 10 * max([tof[i] for tof in self.tof_hist])) # plot occupation for i, occupation_plot in enumerate(self.occupation_plots): occupation_plot.set_xdata(self.times) occupation_plot.set_ydata([occ[i] for occ in self.occupation_hist]) max_occ = max(occ[i] for occ in self.occupation_hist) self.occupation_diagram.set_ylim([0, max(1, max_occ)]) self.occupation_diagram.set_xlim([self.times[0], self.times[-1]]) self.data_plot.canvas.draw_idle() manager = plt.get_current_fig_manager() if hasattr(manager, 'toolbar'): toolbar = manager.toolbar if hasattr(toolbar, 'set_visible'): toolbar.set_visible(False) plt.show() # [:] is necessary so that it copies the # values and doesn't reinitialize the pointer self.time = new_time return False
def detail(request, question_id): simbolo = "ETHBTC" interval = Client.KLINE_INTERVAL_6HOUR start = "1 dec, 2018 00:00:00" end = "31 dec, 2018 00:00:00" klines = get_historical_klines(simbolo, interval, start, end) counter = 1 finale = [] for x in range(0, len(klines)): for each in klines[x]: if (counter % 12) == 8: #ottava riga finale.append(each) counter = counter + 1 results = list(map(float, finale)) ylabel("importi espressi in dollari (USD)") plot(results) xlabel( "la linea gialla tratteggiata indica la media mobile filtrata a 2 giorni" ) ylabel("importi espressi in dollari (USD)") grid(True) data = results data2 = data[:] for i in range(1, len(data) - 1): data2[i] = sum(data[i - 1:i + 7]) / 8.0 plot(data2, '--') data = results data2 = data[:] for i in range(1, len(data) - 1): data2[i] = (sum(data[i - 1:i + 19]) / 20.0) / 4.0 plot(data2, '.') buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png")
def mplimage(request): # Construct the graph x = np.arange(-2, 1.5, .01) y = np.sin(np.exp(2 * x)) plot(x, y) # Store image in a buffer buffer = io.BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png")
def showimage(request): df = pd.read_csv('/home/astra/Desktop/sea/dajngoplot/l/data.csv') sb.set_style("ticks") if x is not None: df = df[df.Country == x] if x == 'nan': df = pd.read_csv('/home/astra/Desktop/sea/dajngoplot/l/data.csv') sb.lmplot(data=df, x="Cumulative Deaths", y="Cumulative Confirmed", hue="Region", fit_reg=False) buffer = BytesIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png")
def maximize_fig(fig=None): """ Try to set the figure fullscreen """ if fig and "canvas" in dir(fig) and fig.canvas: if "Qt4" in pylab.get_backend(): fig.canvas.setWindowState(QtCore.Qt.WindowMaximized) else: mng = pylab.get_current_fig_manager() # attempt to maximize the figure ... lost hopes. win_shape = (1920, 1080) event = Event(*win_shape) try: mng.resize(event) except TypeError: mng.resize(*win_shape) update_fig(fig)
def multi_timeserise_plot(self): DF = self.DF datetime = np.array(DF.index.values) figure = plt.figure(facecolor='white') print "testn" i = 0 n_colums = (DF.shape)[1] for e in DF: try: if i == 0: subplot0 = figure.add_subplot(n_colums,1,1+i) plot0, = subplot0.plot(datetime,DF[e]) subplot0.legend([str(e)],prop={'size':7}) subplot0.xaxis.set_major_locator(MaxNLocator(6)) subplot0.yaxis.set_major_locator(MaxNLocator(4)) setp(subplot0.get_xticklabels(), visible=False) else: subplot = figure.add_subplot(n_colums,1,1+i,sharex=subplot0) plot, = subplot.plot(datetime,DF[e]) subplot.legend( [str(e)],prop={'size':7}) subplot.xaxis.set_major_locator(MaxNLocator(6)) subplot.yaxis.set_major_locator(MaxNLocator(4)) if i + 1 == n_colums: setp(subplot.get_xticklabels(), visible=True) else: setp(subplot.get_xticklabels(), visible=False) except Exception as inst: print type(inst) # the exception instance print inst.args # arguments stored in .args print inst i = i + 1 # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def test_matplotlib(request): x = [1, 2, 3, 4, 5] y = [2, 7, 4, 3, 9] plot(x, y, linewidth=2) xlabel = 'xaxis' ylabel = 'yaxis' title('test') grid(True) buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type='image/png')
def form_valid(self, form): x = form.cleaned_data[u'axis_x'] y = form.cleaned_data[u'axis_y'] x = x.split(', ') y = y.split(', ') plot(x, y, linewidth=2) xlabel('x axis') ylabel('y axis') title('graph') grid(True) buffer = str(io.StringIO()) canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG")
def _set_windowtitle(self,title): """ Helper function to set the title (if not None) of this PyLab plot window. """ # At the moment, PyLab does not offer a window-manager-independent # means for controlling the window title, so what we do is to try # what should work with Tkinter, and then suppress all errors. That # way we should be ok when rendering to a file-based backend, but # will get nice titles in Tk windows. If other toolkits are in use, # the title can be set here using a similar try/except mechanism, or # else there can be a switch based on the backend type. if title is not None: try: manager = plt.get_current_fig_manager() manager.window.title(title) except: pass
def __onclick(self,event): if event.inaxes!=self.WQB.axis: return # wait for clicks in WQBrowser if plt.get_current_fig_manager().toolbar.mode!='': return # toolbar is active self.y = event.ydata; # update spectrum x,y = self._get_line_profile(); self.spectrum.set_ydata(y); # update line views for Line2D,l in self.linemarkers: x=self._get_intersection(Line2D); l.set_xdata([x]*2); # update WQBrowser window self.hline.set_ydata([event.ydata,]*2); self._update();
def averagemonthly_statistic(self,variable="",unit=""): VariableType = self.VariableType DF= self.DF if VariableType == "Cumulative": DF = DF.resample(M, how='sum') else: pass month = (DF.index.month) m1 = DF[month == 1] m2 = DF[month == 2] m3 = DF[month == 3] m4 = DF[month == 4] m5 = DF[month == 5] m6 = DF[month == 6] m7 = DF[month == 7] m8 = DF[month == 8] m9 = DF[month == 9] m10 = DF[month == 10] m11 = DF[month == 11] m12 = DF[month == 12] figure = plt.figure() figure.patch.set_facecolor('white') boxplot([m1.values,m2.values,m3.values,m4.values,m5.values,m6.values,m7.values,m8.values,m9.values,m10.values,m11.values,m12.values]) if variable != "" and unit != "": ylabel(variable + " (" + unit + ")") xlabel("Months") else: pass # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def graph(request):#comment adfa x = [1,2,3,4,5,6] y = [3,5,6,4,4,4] plot(x,y, linewidth=2) xlabel('x axis') ylabel('y axis') title('sample graph') grid(True) buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer,"PNG") pylab.close() return HttpResponse(buffer.getvalue(), mimetype = "image/png")
def varInterpret(request): ''' Creates a matplotlib bar chart of the variant interpretation and gives view. Returns a template of the varType view ''' interpret = Dspclinva.objects.values_list('interpretation') interList = [] for items in interpret: interList.append(items[0]) counts = defaultdict(int) for item in interList: counts[item] += 1 interType = [] values = [] for key, value in counts.iteritems(): interType.append(key) values.append(value) N = len(counts) means = values ind = arange(N) width = 0.35 fig, ax = subplots() rects1 = ax.bar(ind, means, width) subplots_adjust(bottom=0.30) ax.set_ylabel('Number of Variants') ax.set_title('Interpretation of Variants') ax.set_xticks(ind+width) ax.set_xticklabels(interType, size='small', ha='right', rotation = 45) buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png")
def __init__(self, Component, **kwargs): """ """ if not gotMatplotlib: self.Monitoring = False return # List of fields to monitor try: self.FieldKeys = kwargs["MonitorFields"] except: self.FieldKeys = [] if type(self.FieldKeys) is not type([]): self.FieldKeys = [] for key in self.FieldKeys: assert key in Component.State, "\n\n ++++ CliMT.monitor: %s not in component" % key if ndim(Component[key]) == 0: print "\n\n ++++ CliMT.monitor: WARNING: cannot " + "monitor scalar variable %s" % key self.FieldKeys.pop(self.FieldKeys.index(key)) # Decide if we're doing monitoring if len(self.FieldKeys) > 0: self.Monitoring = True else: self.Monitoring = False return # Frequency of monitor updates (default 6 hours) if "MonitorFreq" in kwargs: self.MonitorFreq = kwargs["MonitorFreq"] else: self.MonitorFreq = 6.0 * 60.0 * 60.0 # Clear monitor (if one already set up by a previous instance) pylab.clf() # Set up figure self.Figure = _figureSetUp(self.FieldKeys, Component) # Get figure manager self.manager = pylab.get_current_fig_manager()
def graph(request): zipcodeList = Zipcode.objects.all() zipList = [] zipCount = [] for i in zipcodeList: zipList.append(int(i.zipcode)) zipCount.append(int(i.count)) print i.zipcode print i.count n_groups = len(zipList) index = np.arange(n_groups) rects1 = bar(index, zipCount, .25, alpha=.4, color = 'r', label="Zip Codes") #y = [5,2,6,7,8,9] #bar(zipList,zipCount) #bar(zipList,zipCount) xlabel('Zip Codes') ylabel('Users') title("Zip Codes Serviced by Sunstreet App") xticks(index+.25, zipList, rotation=69, fontsize=12) yticks(fontsize = 20) legend() tight_layout() #grid(True) autolabel(rects1) buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), mimetype="image/png")
def timeseries_plot(self): DateTime = self.DateTime sm_value = self.sm_value ob_value = self.ob_value sm_type = self.sm_type ob_type = self.ob_type sm_color = self.sm_color ob_color = self.ob_color variablename = self.variablename unit = self.unit figure = plt.figure(facecolor='white') subplot = figure.add_subplot(111) if ob_type == "point": observation = subplot.scatter(DateTime,ob_value,color = ob_color) elif ob_type == "line": observation, = subplot.plot(DateTime,ob_value,color = ob_color) if sm_type == "point": simulation = subplot.scatter(DateTime,sm_value, color = sm_color) elif sm_type == "line": simulation, = subplot.plot(DateTime,sm_value, color = sm_color ) subplot.set_ylabel(variablename +"("+unit+")") subplot.set_ylim(min(min(sm_value),min(ob_value)),max(max(sm_value),max(sm_value))) subplot.legend([observation,simulation],["Observation","Simulation"]) subplot.grid() grid(True) subplot.xaxis.set_major_locator(MaxNLocator(8)) # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def graph(request): #x = [1,2,3,4,5] #y = [5,2,6,0,7] #y = "" #response = urllib2.urlopen("http://192.168.43.168:8080/") response = urllib2.urlopen("http://aqi.iitk.ac.in:9000/metrics/station/893?d=03%2F05%2F2015&h=23") #print response.read() #response = urllib2.urlopen("http://0.0.0.0:8080/data.txt") data = response.read() #print "y" y = data.split('\n') print y x = [] length = len(y) # y = [] for i in range(1,length-1): y[i]=float(y[i]) x.append(i) # x = [1,2,3,4,5] # y = [5,2,6,0,7] del y[length-1] del y[0] print len(x) print len(y) print x print y plot(x,y,linewidth=2) xlabel('x axis') ylabel('y axis') title('sample graph') grid(True) buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.fromstring("RGB",canvas.get_width_height(),canvas.tostring_rgb()) graphIMG.save(buffer,"PNG") #print buffer.getvalue() pylab.close() #return render(request,"index.html",{'image':graphIMG}) return HttpResponse(buffer.getvalue(),mimetype="image/png")
def scatter_plot(self): DF = self.DF DF = DF.dropna() data = (DF.as_matrix()).T variable = list(DF.keys()) figuge = scatterplot_matrix(data,variable) figuge.set_facecolor('white') # figure.patch.set_facecolor('white') # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def histogram(self,variable="",unit=""): value = self.Values figure = plt.figure() figure.patch.set_facecolor('white') n, bins, patches = plt.hist(value[~np.isnan(value)], 30, normed=1, facecolor='yellow', alpha = 0.5) if variable != "" and unit != "": ylabel('Probability') xlabel(variable + " (" + unit + ")") else: pass # Store image in a string buffer buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb()) pilImage.save(buffer, "PNG") pylab.close() img = str((buffer.getvalue()).encode('Base64')) return img
def plot_init(data1, data2): sns.set_style("dark") fig = gridspec.GridSpec(2, 2) axarr = [plt.subplot(fig[0, 0]), plt.subplot2grid((2, 2), (1, 0), colspan=2), plt.subplot(fig[0, 1])] img1 = axarr[0].imshow( data1, interpolation="nearest", cmap=plt.cm.ocean, extent=(0.5, np.shape(data1)[0] + 0.5, 0.5, np.shape(data1)[1] + 0.5), ) plt.title("Current Round:" + str(0)) axarr[0].set_ylabel("Give") axarr[0].set_xlabel("Accept") axarr[0].set_title("Distribution of Teams") axarr[1].plot(avg_deal_data1, color="green") axarr[1].set_xlim(0, rounds) axarr[1].set_ylabel("Average Cash per Deal") axarr[1].set_xlabel("Round Number") plt.colorbar(img1, ax=axarr[0], label="Prevalence vs. Uniform") img2 = axarr[2].imshow( data2, interpolation="nearest", cmap=plt.cm.ocean, extent=(0.5, np.shape(data2)[0] + 0.5, 0.5, np.shape(data2)[1] + 0.5), ) plt.title("Current Round:" + str(0)) axarr[2].set_ylabel("Give") axarr[2].set_xlabel("Accept") axarr[2].set_title("Distribution of Teams") axarr[1].plot(avg_deal_data2, color="purple") plt.colorbar(img2, ax=axarr[2], label="Prevalence vs. Uniform") plt.ion() mng = plt.get_current_fig_manager() mng.window.state("zoomed") plt.show() return fig, axarr
def varType(request): ''' Creates a matplotlib pie chart of the variant type and gives view. Returns a template of the varType view ''' varType = Dspclinva.objects.values_list('var_type') varList = [] for items in varType: varList.append(items[0]) counts = defaultdict(int) for item in varList: counts[item] += 1 varType = [] values = [] for key, value in counts.iteritems(): varType.append(key) values.append(value) figure(1, figsize=(10,10)) ax = axes([0.1, 0.1, 0.8, 0.8]) labels = varType fracs = values cmap = plt.cm.jet colors = cmap(np.linspace(0., 1., len(fracs))) p, t = pie(fracs, colors =colors, startangle=90) legend(p, labels, loc="lower left") axis('equal') buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") pylab.close() return HttpResponse(buffer.getvalue(), content_type="image/png")
def graph(request, n): try: n = float(n) conn1 = sqlite3.connect("htmlparser.db") curs1 = conn1.cursor() conn = sqlite3.connect("lemp.db") curs = conn.cursor() a = 1 # ta zmienna wyznaczac bedzie co ktory xticks znajdzie sie na labelu if n > 18: m = int(n) for _ in xrange(5, m): if m % _ == 0: a = _ break else: a = n / 8.0 # jesli _ jest dzielnikiem n to co tyle probek bedzie olabowane else: a = n suma1 = 0 cena = [] for row in curs1.execute("SELECT * FROM ceny"): suma1 += 1 for row in curs1.execute("SELECT * FROM ceny"): suma1 -= 1 if suma1 <= n: cena.append(float(row[1])) kW = [] my_xticks = [] suma = 0 for row in curs.execute("SELECT * FROM pomy"): suma += 1 my_xtics = [] for row in curs.execute("SELECT * FROM pomy"): suma -= 1 if suma <= n: if suma % (n / a) == 0: if n > 160: my_xticks.append(str((row[0][:16]))) else: my_xticks.append(str((row[0].split(" ")[1][:5]))) else: my_xticks.append(str(" ")) kW.append(float(row[1])) kW = np.array(kW) cena = np.array(cena) m = kW * cena * 0.1 x = np.linspace(0, n, n + 1) gcf().subplots_adjust(bottom=0.20) plt.xticks(x, my_xticks, rotation=25) plot(x, m, linewidth=2) gcf().subplots_adjust(bottom=0.15) ylabel("kW * PLN") if n > 140: tekst = "Pokazuje ostatnie %d dni" % ((n - n % 148) / 148) else: tekst = "Pokazuje ostatnie %d h" % ((n - n % 6) / 6) title(tekst) grid(True) buffer = StringIO.StringIO() canvas = pylab.get_current_fig_manager().canvas canvas.draw() # zaladowanie informacji graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb()) graphIMG.save(buffer, "PNG") pylab.close() finally: pass return HttpResponse(buffer.getvalue(), content_type="image/png")