def home_plot2(request): cur.execute( 'select sum(NA_Sales),sum(EU_Sales),sum(JP_Sales) from game_data;') saleList = cur.fetchall() # print(saleSet) # left = range(1,4) height = [saleList[0][0], saleList[0][1], saleList[0][2]] tick_label = ['America', 'Europe', 'Japan'] fig, ax = plt.subplots(figsize=(30, 23)) # ax.bar(left, height, tick_label=tick_label, # width=0.2, color=['red', 'green']) ax.scatter(tick_label, height, s=20**2.5) plt.xlabel('Country', fontsize=35) plt.ylabel('Total Sales', fontsize=30) ax.tick_params(axis="x", labelsize=30) ax.tick_params(axis="y", labelsize=23) plt.title('Scatter Plot of Country Wise Sales(in Millions)', fontsize=30) canvas = FigureCanvasAgg(fig) canvas.print_jpg('games/static/games/image/csbar.jpeg') # print(saleDict) image_data = open("games/static/games/image/csbar.jpeg", "rb").read() return HttpResponse(image_data, content_type="image/png")
def yse_pointing_plot(request,field_name,snid): suggested_pointings,suggested_pointing_names,pointings_for_html,transient,sf = get_yse_pointings_base( field_name,snid) rcParams['figure.figsize'] = (12,6) fig=Figure()#dpi=288,figsize=(1,1)) ax=fig.add_subplot(111) #ax=fig.add_axes([0.2,0.2,0.75,0.65]) canvas=FigureCanvas(fig) ra,dec = [],[] for p,n in zip(suggested_pointings,suggested_pointing_names): d = p.dec.deg*np.pi/180 width_corr = 3.1/np.abs(np.cos(d)) rect = Rectangle(xy=[p.ra.deg-width_corr/2.,p.dec.deg-1.55],width=width_corr,height=3.1,fill=False,lw=5) ax.add_artist(rect) ax.text(p.ra.deg,p.dec.deg,n,ha='center',va='center',fontsize=25) ra += [p.ra.deg] dec += [p.dec.deg] ax.plot(transient.ra,transient.dec,'+',ms=30,mew=5,zorder=100,color='r') ax.text(transient.ra-width_corr/10.,transient.dec+0.15,snid,color='r',fontsize=25,ha='left',va='bottom') ax.set_xlim([np.max(ra)+5,np.min(ra)-5]) ax.set_ylim([np.min(dec)-2,np.max(dec)+2]) ax.set_xlabel(r'$\alpha$',fontsize=15) ax.set_ylabel(r'$\delta$',fontsize=15) response=HttpResponse(content_type='image/png') canvas.print_jpg(response) return response
def getimage(request): fig = Figure() #imp fig, ax = plt.subplots() #imp # x = np.arange(0, 2 * np.pi, 0.01) # s = np.cos(x) ** 2 # plt.plot(x, s) # plt.xlabel('xlabel(X)') # plt.ylabel('ylabel(Y)') # plt.title('Simple Graph!') # plt.grid(True) Country = ['USA', 'Canada', 'Germany', 'UK', 'France'] GDP_Per_Capita = [45000, 42000, 52000, 49000, 47000] # print(Country) xAxis = [i + 0.5 for i, _ in enumerate(Country)] plt.bar(xAxis, GDP_Per_Capita, color='teal') plt.title('Country Vs GDP Per Capita', fontsize=14) plt.xlabel('Country', fontsize=14) plt.ylabel('GDP Per Capita', fontsize=14) plt.xticks([i + 0.5 for i, _ in enumerate(Country)], Country) plt.show() buf = io.BytesIO() plt.savefig(buf, format='png') # plt.close(fig) canvas = FigureCanvas(fig) response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) # fig.savefig(response ) return response
def graficaP(request, funcion, px, py): def getnums(lis): return [float(n) for n in lis] px = px.split(",") py = py.split(",") a = min(getnums(px)) - 3 b = max(getnums(px)) + 3 U, D = sp.symbols('U D') div = lambda U, D: U / D func = sp.sympify(funcion, locals={'div': div}) xDats = [i for i in np.arange(float(a), float(b) + 1.0, 0.3)] yDats = [float('{:.15f}'.format(float(func.subs(x, i)))) for i in xDats] fig = Figure() canvas = FigureCanvasAgg(fig) ax = fig.add_subplot(111) ax.plot(xDats, yDats) ax.plot(getnums(px), getnums(py), 'k*') ax.set(xlabel='eje x', ylabel='eje y', title='Grafica de la Funcion') ax.grid() response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def ant_ant_stat_frame(title_text, full_pol_array, station_names, output_name=None, dpi=50, **kwargs): if output_name is None: fig = figure(figsize=(32,30), dpi=dpi) else: fig=Figure(figsize=(32,30), dpi=dpi) if output_name is None: fig.suptitle(title_text, fontsize=30) else: fig.suptitle(title_text+' '+output_name, fontsize=30) ax1=fig.add_subplot(2,2,1) ant_ant_stat_plot(fig, ax1, title_text+' XX', full_pol_array[:,:,0], station_names, **kwargs) ax2=fig.add_subplot(2,2,2) ant_ant_stat_plot(fig, ax2, title_text+' XY', full_pol_array[:,:,1], station_names, **kwargs) ax3=fig.add_subplot(2,2,3) ant_ant_stat_plot(fig, ax3, title_text+' YX', full_pol_array[:,:,2], station_names, **kwargs) ax4=fig.add_subplot(2,2,4) ant_ant_stat_plot(fig, ax4, title_text+' YY', full_pol_array[:,:,3], station_names, **kwargs) if output_name is not None: canvas = FigureCanvasAgg(fig) if output_name[-4:] in ['.jpg', '.JPG']: canvas.print_jpg(output_name, dpi=dpi, quality=55) else: canvas.print_figure(output_name, dpi=dpi) pass pass
def fetch_city(request): city = request.POST.get('cities') unique_categories = set() categories = [ query['categories'].split(', ') for query in ParsedData.objects.values('categories').filter(city=city) ] for category in categories: for cate in category: unique_categories.add(cate) cat_list = [] for cate in unique_categories: cat_list.append((cate, ParsedData.objects.order_by().filter( city=city, categories__contains=cate).count())) cat_list = sorted(cat_list, key=lambda x: (-x[1], x[0]))[:5] # Data for plotting fig = plt.figure(num=None, figsize=(16, 12), facecolor='w', edgecolor='k') ax = plt.gca() x = list(item[0] for item in cat_list) y = list(item[1] for item in cat_list) ax.bar(x, y, color='gray') ax.set(xlabel='Food Type', ylabel='Number of Restuarant', title='Ranking Cuisine Based on ' + city + " Food") # ax.grid() response = HttpResponse(content_type='image/png') canvas = FigureCanvasAgg(fig) canvas.print_jpg(response) return response
def plot(request, id_sensor, days, pltype): check_url(days=days, id_sensor=id_sensor) if pltype != 'moist' and pltype != 'temp': raise NotFound(detail='only \'moist\' and \'temp\' are available', code=404) from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib.dates import DateFormatter fig = Figure() ax = fig.add_subplot(111) x = [] y1 = [] y2 = [] now = datetime.now() for el in Sensor.objects.filter(date__gte=now - timedelta(days=days), date__lte=now, sensor_id__exact=id_sensor): x.append(el.date) if pltype == 'moist': y1.append(el.vw_30cm) y2.append(el.vw_60cm) else: y1.append(el.t_30cm) y2.append(el.t_60cm) ax.plot_date(x, y1, 'r-', label='глубина 30 см') ax.plot_date(x, y2, '-', label='глубина 60 см') ax.legend() ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) fig.autofmt_xdate() canvas = FigureCanvas(fig) response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def saveWithAxes(img): fig = Figure() axes = fig.add_subplot(111) axes.imshow(img, cmap=cm.Greys_r) canvas = FigureCanvas(fig) # TODO: Need to find a way to avoid this hack! canvas.print_jpg("run.img.tmp.jpg") return numpy.array(Image.open("run.img.tmp.jpg"))
def saveWithAxes(img): fig = Figure() axes = fig.add_subplot(111) axes.imshow(img, cmap=cm.Greys_r) canvas = FigureCanvas(fig) # TODO: Need to find a way to avoid this hack! canvas.print_jpg("run.img.tmp.jpg") return numpy.array(Image.open("run.img.tmp.jpg"))
def finderim(self, request, transient_id, clobber=False): import os from .util import mkFinderChart from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import pylab as plt transient = Transient.objects.get(pk=transient_id) basedir = "%sYSE_App/images/findercharts" % ( djangoSettings.STATIC_ROOT) if not os.path.exists(basedir): os.makedirs(basedir) print(basedir) outputOffsetFileName = '%s/%s/%s.offsetstars.txt' % ( basedir, transient.name, transient.name) outputFinderFileName = '%s/%s/%s.finder.png' % ( basedir, transient.name, transient.name) if not os.path.exists(os.path.dirname(outputFinderFileName)): os.makedirs(os.path.dirname(outputFinderFileName)) #if os.path.exists(outputOffsetFileName) and\ # os.path.exists(outputFinderFileName): # return HttpResponseRedirect(reverse('transient_detail', # args=(transient.id,))) find = mkFinderChart.finder() parser = find.add_options(usage='') options, args = parser.parse_args() options.ra = str(transient.ra) options.dec = str(transient.dec) options.snid = transient.name options.outputOffsetFileName = outputOffsetFileName options.outputFinderFileName = outputFinderFileName find.options = options fig = Figure() if not os.path.exists(options.outputFinderFileName) or \ not os.path.exists(options.outputOffsetFileName) or \ clobber: ax = fig.add_axes([0.2, 0.3, 0.6, 0.6]) canvas = FigureCanvas(fig) ax, offdictlist = find.mkChart(options.ra, options.dec, options.outputFinderFileName, ax=ax, saveImg=True) else: image = mpimg.imread(options.outputFinderFileName) ax = fig.add_axes([0, 0, 1, 1]) ax.set_xticks([]) ax.set_yticks([]) canvas = FigureCanvas(fig) ax.imshow(image) response = django.http.HttpResponse(content_type='image/png') canvas.print_jpg(response) return response
def getWordCloud(request): # 补充停用词 f = open("stopwords-en.txt", mode='r', encoding="UTF-8") li = [] for word in f.readlines(): li.append(word.replace('\n', '')) stopwords = set(STOPWORDS) stopword_list = ['f**k', 'f*****g', 'shit', 'good', 'bad', 'think', 'make', 'know', 'even', 'really', 'one', 'going', 'need', 'got', 'look', 'still'] for word in stopword_list: stopwords.add(word) for word in li: stopwords.add(word) # 连接数据库 sql_conn = sqlite3.connect('reddit_new.sqlite') # 读取post reddit_id = request.GET['id'] subreddit = request.GET['subreddit'] author = request.GET['author'] if reddit_id == "" and subreddit == "" and author == "": messages.warning(request, "Please input something!") return render(request, "query.html") # 查找 if reddit_id != "" and subreddit == "" and author == "": sql_query = "select body from reddit where id = '%s'"%(reddit_id) elif reddit_id == "" and subreddit != "" and author == "": sql_query = "select body from reddit where subreddit = '%s'"%(subreddit) elif reddit_id == "" and subreddit == "" and author != "": sql_query = "select body from reddit where author = '%s'"%(author) elif reddit_id != "" and subreddit != "" and author == "": sql_query = "select body from reddit where subreddit = '%s' and id = '%s'"%(subreddit,reddit_id) elif reddit_id == "" and subreddit != "" and author != "": sql_query = "select body from reddit where subreddit = '%s' and author = '%s'"%(subreddit,author) elif reddit_id != "" and subreddit == "" and author != "": sql_query = "select body from reddit where id = '%s' and author = '%s'"%(reddit_id,author) elif reddit_id != "" and subreddit != "" and author != "": sql_query = "select body from reddit where id = '%s' and author = '%s' and subreddit = '%s'"%(reddit_id,author,subreddit) df = pd.read_sql(sql_query, sql_conn) # 文本生成 text = "".join(list(df['body'])).lower() # 词云生成 wc = WordCloud(background_color="white", stopwords=stopwords, max_words=200, max_font_size=120, mask=bg_pic, random_state=42) wc.generate(text) fig = plt.figure() plt.imshow(wc, interpolation="bilinear") plt.axis("off") # 转HTML canvas = FigureCanvasAgg(fig) response = HttpResponse(content_type='image/png') canvas.print_jpg(response) plt.close(fig) return response
def lineTemp(response): fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) data_df = pd.read_csv("MainApp/static/ourdata/scv_file2.csv") data_df = pd.DataFrame(data_df) data_df.plot(ax=ax, y='Temperature', x='Severity') response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def histPop(response): fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) data_df = pd.read_csv("MainApp/static/ourdata/scv_file2.csv") data_df = pd.DataFrame(data_df) data_df.plot(ax=ax, y='Population', kind='hist') response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def boxAge(response): fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) data_df = pd.read_csv("MainApp/static/ourdata/scv_file2.csv") data_df = pd.DataFrame(data_df) data_df.boxplot(ax=ax, column='Median_Age', by='Severity') response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def mplimage(request): fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) x = np.arange(-4, 0.5, .02) y = np.sin(np.exp(2 * x)) ax.plot(x, y) s = io.StringIO() response = HttpResponse(s.getvalue(), content_type='image/jpg') canvas.print_jpg(response) return response
def ret_graph(): fig = Figure() canvas = FigureCanvas(fig) df1[df1.columns].plot(kind='line') buf = io.BytesIO() plt.savefig(buf, format='png') plt.close(fig) response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def seaPlot(response): fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) data_df = pd.read_csv("MainApp/static/ourdata/scv_file2.csv") del data_df['Unnamed: 0.1'] del data_df['Unnamed: 0'] corr = data_df.corr() sns.heatmap(corr, ax=ax) response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def thirteen(request): if request.method == 'POST': form = graphcountry(request.POST) form.fields['competition'].choices = [(i, i) for i in choice2] if form.is_valid(): b = form.cleaned_data['competition'] import mysql.connector mydb = mysql.connector.connect(host="localhost", user="******", passwd="albertbolt23", database="sports2", auth_plugin='mysql_native_password') mycursor = mydb.cursor() sql = "SELECT place_of_birth,count(*) FROM project_records,project_event,project_competition,project_sportsman where project_records.event_id_id=project_event.id and project_event.Competition_name_id=project_competition.name and project_records.player_name_id=project_sportsman.name and project_competition.name='%s' group by place_of_birth order by count(*)" % ( b) mycursor.execute(sql) k = mycursor.fetchall() a = [] for i in k: for j in i: a.append(j) a23 = [] a24 = [] for i in range(0, len(a), 2): a23.append(a[i]) for i in range(1, len(a), 2): a24.append(a[i]) y_pos = np.arange(len(a23)) fig = Figure(figsize=(10, 5)) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) y_pos = np.arange(len(a23)) ax.barh(a23, a24, align='center', alpha=0.5) ax.set_xlabel('No of medals') ax.set_ylabel('Countries') response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def line_plot(request, year=date.today().year, month=date.today().month): """ Function based view that creates a line graph plotting the daily spendings for the current month. """ # creating the data to be presented in the graph x = [] y = [] if month == 2: if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0): days = np.arange(1, 29, 1) else: days = np.arange(1, 28, 1) elif month in [1, 3, 5, 7, 8, 10, 12]: days = np.arange(1, 31, 1) elif month in [4, 6, 9, 11]: days = np.arange(1, 30, 1) for day in days: x.append(day) y.append( UserDetails.objects.filter( user=request.user, date_added__year=year, date_added__month=month, date_added__day=day).aggregate(suma=Sum('cost'))['suma'] or 0.00) # creating the figure to plot the graph fig = Figure() ax = fig.add_subplot(111) # creating the axes ax.plot(x, y) fig.suptitle('Your daily spendings', fontsize=20) ax.set(xlabel='day', ylabel='spendings (€)') ax.grid() # FigureCanvas is the area onto which the figure is drawn canvas = FigureCanvas(fig) # creating the response as image type jpeg response = HttpResponse(content_type="image/jpg") canvas.print_jpg(response) return response
def stat3(request): f = Figure() co = sqlite3.connect('./db.sqlite3') data = pd.read_sql_query('SELECT count(date_demande),date_demande FROM forms_demande GROUP BY date_demande;',co) df = pd.DataFrame(data) f, ax = plt.subplots() df.plot(kind = 'bar', color = 'limegreen',ax=ax, x = 'date_demande',figsize=(11,11), title = "Nombre de commandes par jour" ) plt.xlabel('Date') plt.ylabel("Nombre de commandes") plt.legend('') fig, ax = plt.subplots() df.plot(ax=ax) canvas = FigureCanvasAgg(f) response = HttpResponse(content_type='image\jpg') canvas.print_jpg(response) plt.close(f) return response
def stat2(request): f = Figure() co = sqlite3.connect('./db.sqlite3') data = pd.read_sql_query('SELECT count(nom), ville FROM forms_compte GROUP BY nom;',co) df = pd.DataFrame(data) f, ax = plt.subplots() df.plot(kind = 'bar', color = 'gold',ax=ax, x = 'ville',figsize=(11,11), title = "Nombre de foyers par ville" ) plt.xlabel('Ville') plt.ylabel("Nombre de foyers") plt.legend('') fig, ax = plt.subplots() df.plot(ax=ax) canvas = FigureCanvasAgg(f) response = HttpResponse(content_type='image\jpg') canvas.print_jpg(response) plt.close(f) return response
def histogram(img): fig = Figure() axes = fig.add_subplot(111) if len(img.shape) == 2 or img.shape[2:][0] == 1: axes.hist(img.flatten(), 300, color='blue', edgecolor='none') else: img = cv2.cvtColor(img, cv2.cv.CV_RGB2HSV) axes.hist([img[...,0], img[...,1], img[...,2]], 128, color=['red', 'green', 'blue'], edgecolor='none') axes.legend(('Hue', 'Saturation', 'Value')) #axes.legend(('Red', 'Green', 'Blue')) # If hsv, should look something like this. # axes.hist([img[...,0], img[...,1], img[...,2]], 300, color=['r','g','b']) axes.grid(True) setp(axes.get_yticklabels(), visible=False) canvas = FigureCanvas(fig) canvas.print_jpg("run.hist.tmp.jpg") return Image.open("run.hist.tmp.jpg")
def plot(request): text = request.GET.get('name') value = Game.objects.get(name=text) left = [1, 2, 3, 4] height = [ value.NA_Sales, value.EU_Sales, value.JP_Sales, value.Other_Sales ] tick_label = ['America', 'Europe', 'Japan', 'Other'] fig, ax = plt.subplots() ax.bar(left, height, tick_label=tick_label, width=0.8, color=['red', 'green']) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title('Bar Graph of Sales in Country(in Millions)') canvas = FigureCanvasAgg(fig) canvas.print_jpg('games/static/games/image/bar.jpeg') labels = tick_label sizes = height explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs') fig1, ax1 = plt.subplots() ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis( 'equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.title('Pie Chart of Sales') plt.legend(loc="upper left") canvas1 = FigureCanvasAgg(fig1) canvas1.print_jpg('games/static/games/image/pie.jpeg') return render(request, 'games/graph.html')
def search(request): if request.method == 'POST': search_id = request.POST.get('textfield', None) try: queried_data = ParsedData.objects.values('city').annotate( type_count=models.Sum(models.F('stars') * models.F('review_count'), output_field=models.IntegerField()) / models.Count('business_id')).filter( categories__contains=search_id).order_by( '-type_count')[:10] diction = {} for data in queried_data: diction[data['city']] = data['type_count'] # Data for plotting fig = plt.figure(num=None, figsize=(16, 12), facecolor='w', edgecolor='k') ax = plt.gca() plt.xticks(rotation=45) x = list(diction.keys()) y = list(diction.values()) ax.bar(x, y, color='gray') ax.set(xlabel='Cities', ylabel='Score', title='Ranking Cities Based on ' + search_id + " Food") # ax.grid() response = HttpResponse(content_type='image/png') canvas = FigureCanvasAgg(fig) canvas.print_jpg(response) return response except ValueError: return HttpResponse(str(ValueError) + "Invalid Search.") else: return HttpResponse("Invalid Post.")
def timeseries_station_page(ms, station_name, time_slots, data, fn=abs, output_name=None): dpi=50 if output_name is None: fig = figure(figsize=(32,24), dpi=dpi) else: fig = Figure(figsize=(32,24), dpi=dpi) station_name_list = list(ms.tables['antennae']['NAME']) station_id = station_name_list.index(station_name) num_ant = len(ms.tables['antennae']) tsn = time_slots-time_slots[0] pol_names = corr_type(ms.tables['polarization']['CORR_TYPE'][0]) ref_freq_mhz = ms.tables['spectral_windows'][0]['REF_FREQUENCY']/1.e6 fig.suptitle(ms.msname+': '+fn.__name__+'(vis) with '+station_name+' at %3.2f MHz' % (ref_freq_mhz,), fontsize='large') median_amp = ma.median(ma.mean(ma.median(fn(data[station_id,:,0::3,:]), axis=-1), axis=-1), axis=-1) for id2,name in enumerate(station_name_list): ax = fig.add_subplot(ceil(num_ant/4.0),4, id2+1) ax.plot(tsn, fn(data[station_id,id2,0,:]), c='blue' , label=pol_names[0]) ax.plot(tsn, fn(data[station_id,id2,1,:]), c='green' , label=pol_names[1]) ax.plot(tsn, fn(data[station_id,id2,2,:]), c='purple', label=pol_names[2]) ax.plot(tsn, fn(data[station_id,id2,3,:]), c='red' , label=pol_names[3]) ax.grid() ax.set_ylabel(station_name_list[id2], rotation='horizontal') ax.set_ylim(0.0, 3*median_amp) ax.set_yticklabels([]) if id2 < len(station_name_list)-4: ax.set_xticklabels([]) else: ax.set_xlabel('Time [s]') pass fig.subplots_adjust(hspace=0.0, top=0.95, bottom=0.04) if output_name is not None: canvas = FigureCanvasAgg(fig) if output_name[-4:] in ['.jpg', '.JPG']: canvas.print_jpg(output_name, dpi=dpi, quality=55) else: canvas.print_figure(output_name, dpi=dpi) pass pass
def grafica(request, funcion, a, b): U, D = sp.symbols('U D') div = lambda U, D: U / D func = sp.sympify(funcion, locals={'div': div}) xDats = [i for i in np.arange(float(a), float(b) + 1.0, 0.3)] yDats = [float('{:.15f}'.format(float(func.subs(x, i)))) for i in xDats] fig = Figure() canvas = FigureCanvasAgg(fig) ax = fig.add_subplot(111) ax.plot(xDats, yDats) ax.set(xlabel='eje x', ylabel='eje y', title='Grafica de la Funcion') ax.grid() response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def histogram(img): fig = Figure() axes = fig.add_subplot(111) if len(img.shape) == 2 or img.shape[2:][0] == 1: axes.hist(img.flatten(), 300, color='blue', edgecolor='none') else: img = cv2.cvtColor(img, cv2.cv.CV_RGB2HSV) axes.hist([img[..., 0], img[..., 1], img[..., 2]], 128, color=['red', 'green', 'blue'], edgecolor='none') axes.legend(('Hue', 'Saturation', 'Value')) #axes.legend(('Red', 'Green', 'Blue')) # If hsv, should look something like this. # axes.hist([img[...,0], img[...,1], img[...,2]], 300, color=['r','g','b']) axes.grid(True) setp(axes.get_yticklabels(), visible=False) canvas = FigureCanvas(fig) canvas.print_jpg("run.hist.tmp.jpg") return Image.open("run.hist.tmp.jpg")
def home_plot(request): yearSet = set() curSet = [] cur.execute('select year from game_data') curSet = cur.fetchall() for each in curSet: yearSet.add(each[0]) # print(yearSet) cur.execute('select year, sum(global_sales) from game_data group by year') saleList = cur.fetchall() saleDict = {} for each in saleList: saleDict[each[0]] = each[1] keys = [] for each in list(saleDict.keys()): keys.append(each) # print(saleDict.values()) left = range(1, 38) height = saleDict.values() tick_label = keys fig, ax = plt.subplots(figsize=(30, 23)) ax.bar(left, height, tick_label=tick_label, width=0.8, color=['red']) plt.xlabel('Years', fontsize=30) plt.ylabel('Global Sales', fontsize=30) ax.tick_params(axis="x", labelsize=23, rotation=90) ax.tick_params(axis="y", labelsize=23) plt.title('Bar Graph of Global Sales in Years(in Millions)', fontsize=30) canvas = FigureCanvasAgg(fig) canvas.print_jpg('games/static/games/image/gsbar.jpeg') # print(saleDict) image_data = open("games/static/games/image/gsbar.jpeg", "rb").read() return HttpResponse(image_data, content_type="image/png")
def plotResults(request, question_id): fig = Figure() ax = fig.add_subplot(1, 1, 1) p = get_object_or_404(Question, pk=question_id) # Get the poll object from django x = matplotlib.numpy.arange(1, p.choice_set.count()) choices = p.choice_set.all() votes = [choice.votes for choice in choices] sum_votes = sum(votes) names = [choice.choice_text for choice in choices] votes_percentage = [choice.votes * 100 / sum_votes for choice in choices] numTests = p.choice_set.count() ind = matplotlib.numpy.arange(numTests) # the x locations for the groups cols = ['purple', 'yellow', 'red'] * 10 cols = cols[0:len(ind)] ax.barh(names, votes_percentage, color=cols, align='center') ax.set_yticks(ind + 0.1) ax.set_yticklabels(names) ax.set_ylabel("Choices") ax.set_xlabel("Votes in Percentage(%)") title = "Dynamically Generated Results -- Plotted Bar Graph" ax.set_title(title) #ax.grid(True) canvas = FigureCanvas(fig) response = HttpResponse(content_type='image/jpg') canvas.print_jpg(response) return response
def home_plot5(request): cur.execute( 'select platform, count(platform) from game_data group by platform;') saleList = cur.fetchall() saleDict = {} for each in saleList: saleDict[each[0]] = each[1] keys = [] for each in list(saleDict.keys()): keys.append(each) # print(saleDict.values()) left = range(1, 25) height = saleDict.values() tick_label = keys fig, ax = plt.subplots(figsize=(30, 23)) ax.bar(left, height, tick_label=tick_label, width=0.8, color=['red', 'green']) # ax.plot(tick_label, height) plt.xlabel('Platform', fontsize=30) plt.ylabel('Count', fontsize=30) ax.tick_params(axis="x", labelsize=23, rotation=90) ax.tick_params(axis="y", labelsize=23) plt.title('Count of games per Platform', fontsize=30) canvas = FigureCanvasAgg(fig) canvas.print_jpg('games/static/games/image/ggbar.jpeg') # print(saleDict) image_data = open("games/static/games/image/ggbar.jpeg", "rb").read() return HttpResponse(image_data, content_type="image/png")
def uv_only_plot(request): ra,dec,sr = [float(request.GET.get(_)) for _ in ['ra', 'dec', 'sr']] field = request.GET.get('field') width = 600 work = uv_only_worker(ra, dec, sr) value = work['galex']['table'][field] nidx = work['nidx'] fig = Figure(facecolor='white', figsize=(width/72, width*0.5/72), dpi=72, tight_layout=True) ax = fig.add_subplot(111) ax.hist(value, bins=np.arange(15, 25, 0.5), alpha=0.5, label='All'); ax.hist(value[nidx], bins=np.arange(15, 25, 0.5), alpha=0.5, label='Not matched'); ax.set_xlabel(field) ax.set_title('ra=%s dec=%s sr=%s' % (ra, dec, sr)) ax.legend() canvas = FigureCanvas(fig) response = HttpResponse(content_type='image/jpeg') canvas.print_jpg(response) return response
def update_picture_self_coords(image, lidar_points, self_position, only_nearby_meters, additional_points): fig = Figure(figsize=figsize_from_image_size(image)) canvas = FigureCanvas(fig) ax = fig.gca() x_points = [x[0] for x in lidar_points] y_points = [x[1] for x in lidar_points] ax.scatter(x_points, y_points, marker='o', s=5, c='b') if self_position is None: ax.scatter([0], [0], marker='o', s=50, c='r') else: rect = patches.Rectangle((self_position['x'], self_position['y']), self_position['w'], self_position['h'], linewidth=3, edgecolor='r', facecolor='none') ax.add_patch(rect) if additional_points is not None: ax.scatter(additional_points['x'], additional_points['y'], marker='o', s=25, c='g') ax.set_xlim(-only_nearby_meters, only_nearby_meters) ax.set_ylim(-only_nearby_meters, only_nearby_meters) ax.grid(which='both', linestyle='--', alpha=0.5) canvas.draw() jpeg = BytesIO() canvas.print_jpg(jpeg) image.value = jpeg.getvalue()
def station_gain_bar_chart(ms, station_name, time_slots, data, output_name= None): dpi=50 if output_name is None: fig = figure(figsize=(38,24), dpi=dpi) else: fig = Figure(figsize=(38,24), dpi=dpi) station_name_list = list(ms.tables['antennae']['NAME']) num_stations = len(station_name_list) station_id = station_name_list.index(station_name) ref_freq_mhz = ms.tables['spectral_windows'][0]['REF_FREQUENCY']/1.e6 is_autocorrelation = array([station_name == name for name in ms.tables['antennae']['NAME']]) noise = ma.array(data[station_id,:, 1:3,:].imag.std(axis=-1).mean(axis=-1), mask = is_autocorrelation) sig = median(abs(data[station_id, :, :, :]),axis=-1) signal = ma.array(sig, mask = is_autocorrelation[:, newaxis]*ones((num_stations, 4))) ax = fig.add_subplot(1,1,1) xx_bars = ax.bar(arange(len(station_name_list))-0.4, signal[:, 0], width=0.2, color='blue', label='xx') xy_bars = ax.bar(arange(len(station_name_list))-0.2, signal[:, 1], width=0.2, color='lightblue', label='xy') yx_bars = ax.bar(arange(len(station_name_list)) , signal[:, 2], width=0.2, color='lightpink', label='yx') yy_bars = ax.bar(arange(len(station_name_list))+0.2, signal[:, 3], width=0.2, color='red', label='yy') for x_pos, name in enumerate(station_name_list): if name != station_name: ax.text(x_pos, signal[x_pos,:].max()*1.02, name, rotation='vertical', horizontalalignment='center', verticalalignment='bottom', fontsize=25) ax.text(x_pos, signal[x_pos,:].max()*-0.01, name, rotation='vertical', horizontalalignment='center', verticalalignment='top', fontsize=25) else: ax.text(x_pos, 0.0, ' Reference station: '+name, rotation='vertical', horizontalalignment='center', verticalalignment='bottom', fontsize=25) ax.set_xlabel('Station', fontsize=40) ax.set_ylabel('Visibility amplitude', fontsize=40) ax.set_ylim(0, ma.max(signal)*1.2) ax.set_xlim(-1.0, num_stations) ax.set_xticklabels([]) ax.set_title('%s:\nVis. amp. with station %s at %5.2f MHz' % (ms.msname, station_name, ref_freq_mhz), fontsize=40) old_legend_fontsize = rcParams['legend.fontsize'] rcParams.update({'legend.fontsize': 25}) legend_instance = ax.legend() for label in ax.get_yticklabels(): label.set_fontsize(40) if output_name is not None: canvas = FigureCanvasAgg(fig) if output_name[-4:] in ['.jpg', '.JPG']: canvas.print_jpg(output_name, dpi=dpi, quality=55) else: canvas.print_figure(output_name, dpi=dpi) pass rcParams.update({'legend.fontsize': old_legend_fontsize})