def plotRecognitionErrors(): N = 5 theta = radar_factory(N, frame='polygon') data = getRecognitionErrorData() spoke_labels = data.pop(0) fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) fig.text(0.15, 0.425, 'RE1: Inadequate Surveillance') fig.text(0.15, 0.40, 'RE2: Internal Distraction') fig.text(0.15, 0.375, 'RE3: External Distraction') fig.text(0.15, 0.35, 'RE4: Inattention') fig.text(0.15, 0.325, 'RE5: Unknown Recognition Error') colors = ['b', 'r'] # Plot the four cases from the example data on separate axes for n, (title, case_data) in enumerate(data): ax = fig.add_subplot(2, 2, n + 1, projection='radar') plt.rgrids([10, 20, 30, 40, 50]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(case_data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) plt.show()
def plot_list(points, primes=False, labels=False, file_name=""): max_len = 0 for pt in points: length, angle = pt.polar_form() if (length > max_len): max_len = length r = pt.real i = pt.imaginary if pt.is_prime(): plt.polar(angle, length, 'ro') else: plt.polar(angle, length, 'bo') if (labels): plt.text(angle, length, str(multiple), horizontalalignment='center', verticalalignment='bottom') plt.thetagrids(range(0, 360, 60), ('1', '1+ω', 'ω', '-1', '-ω-1', '-ω')) plt.rgrids(np.arange(0, max_len, max_len / 10), labels=[]) if file_name != "": plt.savefig(file_name) plt.clf() else: plt.show() return plt
def plotPerformanceErrors(): N = 7 theta = radar_factory(N, frame='polygon') data = getPerformanceErrorData() spoke_labels = data.pop(0) fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) fig.text(0.075, 0.425, 'PE1: Overcompensation') fig.text(0.075, 0.40, 'PE2: Poor Directional Control') fig.text(0.075, 0.375, 'PE3: Sleep') fig.text(0.075, 0.35, 'PE4: Heart Attack or Other Physical Impairment') fig.text(0.075, 0.325, 'PE5: Panic/Freezing') fig.text(0.075, 0.30, 'PE6: Unknown Performance Error') fig.text(0.075, 0.275, 'PE7: Unknown Critical Nonperformance Error') colors = ['b', 'r'] # Plot the four cases from the example data on separate axes for n, (title, case_data) in enumerate(data): ax = fig.add_subplot(2, 2, n + 1, projection='radar') plt.rgrids([5, 10, 15, 20, 25, 30]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(case_data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) plt.show()
def radar_plot(): """ radar plot """ # 生成测试数据 labels = np.array(["A组", "B组", "C组", "D组", "E组", "F组"]) data = np.array([68, 83, 90, 77, 89, 73]) theta = np.linspace(0, 2*np.pi, len(data), endpoint=False) # 数据预处理 data = np.concatenate((data, [data[0]])) theta = np.concatenate((theta, [theta[0]])) # 画图方式 plt.subplot(111, polar=True) plt.title("雷达图", fontproperties=myfont) # 设置"theta grid"/"radar grid" plt.thetagrids(theta*(180/np.pi), labels=labels, fontproperties=myfont) plt.rgrids(np.arange(20, 100, 20), labels=np.arange(20, 100, 20), angle=0) plt.ylim(0, 100) # 画雷达图,并填充雷达图内部区域 plt.plot(theta, data, "bo-", linewidth=2) plt.fill(theta, data, color="red", alpha=0.25) # 图形显示 plt.show() return
def plot_radar(example_data,nVar): N = nVar theta = radar_factory(N, frame='polygon') data = example_data people_Num=len(data) spoke_labels = data.pop('column names') fig = plt.figure(figsize=(9, 2*people_Num)) fig.subplots_adjust(wspace=0.55, hspace=0.10, top=0.95, bottom=0.05) colors = ['b', 'r', 'g', 'm', 'y'] for n, title in enumerate(data.keys()): ax = fig.add_subplot(int(people_Num/3)+1, 3, n+1, projection='radar') plt.rgrids([0.2, 0.4, 0.6, 0.8]) plt.setp(ax.get_yticklabels(), visible=False) plt.ylim([0,1]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),color='b', horizontalalignment='center', verticalalignment='center',fontproperties=zhfont) for d, color in zip(data[title], colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) plt.subplot(int(people_Num/3)+1, 3, 1) plt.figtext(0.5, 0.965, '战力统计',fontproperties=zhfont, ha='center', color='black', weight='bold', size='large') plt.show()
def plot(self, legend=True, fig_title=None): theta = radar_factory(self.get_data_size(), frame="polygon") fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) colors = ["b", "r", "g", "m", "y"] # Plot the four cases from the example data on separate axes for n, title in enumerate(self._data.keys()): ax = fig.add_subplot(2, 2, n + 1, projection="radar") plt.rgrids([0.02, 0.04, 0.06, 0.08]) ax.set_title( title, weight="bold", size="medium", position=(0.5, 1.1), horizontalalignment="center", verticalalignment="center", ) for d, color in zip(self._data[title], colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(self._labels) if legend: self.plot_legend() if fig_title is not None: self.plot_title(fig_title) plt.show()
def plot_radar(data, titles, title='', legends=None, normalize=False, colors=None, fill=True): r = data.copy() if normalize: r.loc[:, titles] = MaxAbsScaler().fit_transform(r.loc[:, titles]) case_data = r case_data.reset_index(inplace=True) theta = radar_factory(len(titles), frame='polygon') fig = plt.figure(figsize=(7, 7)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) if colors is None: colors = "bgrcmykw" ax = fig.add_subplot(1, 1, 1, projection='radar') plt.rgrids([0.2, 0.4, 0.6, 0.8]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(case_data[titles].values, colors): ax.plot(theta, d, color=color) if fill: ax.fill(theta, d, facecolor=color, alpha=0.25) # ax.set_rmax(1.0) ax.set_varlabels(titles) # add legend relative to top-left plot if legends: plt.subplot(1, 1, 1) labels = legends legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.2) plt.setp(legend.get_texts(), fontsize=15) plt.setp(legend.get_lines(), linewidth=13, alpha=0.50) plt.show()
def plot_model(data): N = 5 #初始化 theta = radar_factory(N, frame='polygon') fig = plt.figure(figsize=(8, 6)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) colors = ['b', 'r', 'g', 'm', 'y'] # Plot the four cases from the example data on separate axes #['L', 'R', 'F', 'M', 'C']('ZL', 'ZC', 'ZM', 'ZF', 'ZR') spoke_labels = ('ZL', 'ZC', 'ZM', 'ZF', 'ZR') ax = fig.add_subplot(111, projection='radar') plt.rgrids([0.1, 0.5, 1, 1.5, 2.0, 2.5]) ax.set_title(u'客户群分析', weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) labels = ('1', '2', '3', '4', '5') legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1) plt.setp(legend.get_texts(), fontsize='small') plt.show()
def single(multiple, total_num): fig = plt.figure(0, figsize=(10, 10)) fig.show() """theta's, r's""" plt.polar([i * np.pi * 2 / total_num for i in range(total_num + 1)], [1] * (total_num + 1), c=(1, 0, 0)) plt.thetagrids([None]) plt.rgrids([30]) plt.autoscale(False) for i in range(1, total_num + 1): plt.polar((i * np.pi * 2 / total_num, ((i * multiple) % total_num) * np.pi * 2 / total_num), [1] * 2, c=(0, 0, 0)) with plt.xkcd(randomness=0): plt.annotate(i, xy=(i * np.pi * 2 / total_num, 1.05), horizontalalignment='center', verticalalignment='center') plt.show()
def plot_graph(var_stats, var_clean, var_evil): try: import matplotlib.pyplot as plt except: sys.sderr.write("matploitlib not found") sys.exit(1) N = 4 # az AZ 09 other theta = radar_factory(N, frame='circle') spoke_labels = ["[a-z]", "[A-Z]", "[0-9]", "[other]"] fig = plt.figure(figsize=(15, 8)) fig.subplots_adjust(wspace=0.20, hspace=0.20, top=1.00, bottom=0.00, left=0.05, right=0.93) """ # Overall ax = fig.add_subplot(2, 2, 3, projection='radar') plt.rgrids([20, 40, 60, 80]) ax.set_title("Overall", weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for varname, varfeatures in var_stats.iteritems(): d = [ varfeatures['az'], varfeatures['AZ'], varfeatures['09'], varfeatures['other'] ] color = 'green' if varname in var_clean else 'red' ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) """ # Clean ax = fig.add_subplot(1, 2, 1, projection='radar') plt.rgrids([20, 40, 60, 80]) ax.set_title("Clean", weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for varname, varfeatures in var_clean.iteritems(): d = [ varfeatures['az'], varfeatures['AZ'], varfeatures['09'], varfeatures['other'] ] ax.plot(theta, d, color='green') ax.fill(theta, d, facecolor='green', alpha=0.25) ax.set_varlabels(spoke_labels) # Evil ax = fig.add_subplot(1, 2, 2, projection='radar') plt.rgrids([20, 40, 60, 80]) ax.set_title("Evil", weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for varname, varfeatures in var_evil.iteritems(): d = [ varfeatures['az'], varfeatures['AZ'], varfeatures['09'], varfeatures['other'] ] ax.plot(theta, d, color='red') ax.fill(theta, d, facecolor='red', alpha=0.25) ax.set_varlabels(spoke_labels) plt.figtext(0.5, 0.965, 'Variable/Function name features distribution', ha='center', color='black', weight='bold', size='large') plt.figtext(0.5, 0.935, 'PRICK v0.1', ha='center', color='black', weight='normal', size='medium') plt.show()
def sonar_graph(ping_readings): #print "ping reading:", ping_readings #print type(ping_readings[1]) # force square figure and square axes looks better for polar, IMO fig = figure(figsize=(3.8,3.8)) ax = P.subplot(1, 1, 1, projection='polar') P.rgrids([28, 61, 91]) ax.set_theta_zero_location('N') ax.set_theta_direction(-1) try: theta = 346 angle = theta * np.pi / 180.0 radii = [ping_readings[0]] width = .15 bars1 = ax.bar(0, 100, width=0.001, bottom=0.0) #print "theta, radii, width: ", theta, radii, width bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') theta = 6 angle = theta * np.pi / 180.0 radii = [ping_readings[1]] width = .15 bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') theta = 86 angle = theta * np.pi / 180.0 radii = [ping_readings[2]] width = .15 bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') theta = 266 angle = theta * np.pi / 180.0 radii = [ping_readings[3]] width = .15 bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') img_to_return = fig2img(fig) P.close(fig) return img_to_return except: print "Sonar data error... can't graph" pass #print "finshed graph" #pil_img = fig2img(fig) #sonar_image = pil_img #print type(pil_img), pil_img #sonar_image = PILtoCV_4Channel(pil_img) #cv.ShowImage("Sonar", sonar_image ) #cv.MoveWindow ('Sonar',50 ,50 ) #time.sleep(.01) #cv.WaitKey(10) #enable line below to make basestation work 12/13/2012 #fig.savefig('sonar_image.png') #Image.open('sonar_image.png').save('sonar_image.jpg','JPEG') #print "finished saving" #stop #garbage cleanup #fig.clf() #gc.collect() #del fig P.close(fig)
def stereoProjPlot(phi, psi, int=None, lineSpec='', titleText=None, maxPsi=90, fig=None, partPlot=False, thetaStep=None, rStep=None, rMax=None, cbarOri='vertical'): # only allow defined psi values phi = phi[(psi >= -maxPsi) & (psi <= maxPsi)] if int is not None: int = int[(psi >= 0) & (psi <= maxPsi)] psi = psi[(psi >= 0) & (psi <= maxPsi)] #h = polarplot(np.deg2rad(phi),tand(0.5 * psi),lineSpec) if fig is None: fig = plt.figure() ax = fig.add_subplot(111, projection='polar') if int is None: #c = ax.scatter(np.deg2rad(phi), bc.tand(0.5 * psi)) if len(lineSpec) > 0: c = plt.polar(np.deg2rad(phi), bc.tand(0.5 * psi), lineSpec) else: c = plt.polar(np.deg2rad(phi), bc.tand(0.5 * psi)) else: c = ax.scatter(np.deg2rad(phi), bc.tand(0.5 * psi), c = int, cmap='jet') fig.colorbar(c, orientation=cbarOri) if thetaStep is not None: plt.thetagrids(np.array(range(0, 360, thetaStep))) if rMax is not None and rStep is not None: plt.rgrids(np.array(range(0, rMax, rStep))) if not partPlot: c[0].axes.set_ylim(0, 1) if titleText is not None: ax.set_title(titleText) plt.tight_layout() # layout without overlapping plt.show() return fig, c, ax
def _generate_complexity_stats(fig, stats): """ Synopsis: Generates a complexity statistic png in the root folder from the given stats. :param fig: current matplotlib figure :param stats: stats file containing data from which to generate statistics """ if stats['nodes_over_time']: theta = _radar_factory(dimensions=3) colors = ['orange', 'white', 'white'] title = [ 'Model complexity', '\nData complexity', '\nMethod complexity' ] case_data = [[ stats['model_complexity_over_time'][-1], stats['class_data_complexity'][-1], stats['class_function_complexity'][-1] ], [0, 0, 0], [1, 1, 1]] ax = fig.add_subplot(111, projection='radar') plt.rgrids([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9], [''] * 9) for d, color in zip(case_data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(title) else: plt.text(0.5, 0.5, 'Not enough data', horizontalalignment='center', verticalalignment='center', bbox=dict(facecolor='red', alpha=0.5)) plt.savefig('complexity.png', dpi=90, facecolor='#411f48') plt.clf()
def polar_coo_A(): co_A = np.zeros(t.size, dtype=complex) counter_A = np.zeros(t.size, dtype=complex) co_A.real = -co_A_P(t) co_A.imag = -co_A_S(t) counter_A.real = -counter_A_P(t) counter_A.imag = -counter_A_S(t) co_A_theta = np.angle(co_A) co_A_abs = abs(co_A) counter_A_theta = np.angle(counter_A) counter_A_abs = abs(counter_A) plt.figure(figsize=(10, 5)) plt.subplot(121, polar=True) plt.plot(co_A_theta, co_A_abs, linewidth=1.5, color="y", label="Co-rotating") plt.rgrids(np.arange(0.1, 1.1 * max(co_A_abs), 0.3), angle=180) plt.legend(loc=(0.7, 1), prop={'size': 12}) plt.subplot(122, polar=True) plt.plot(counter_A_theta, counter_A_abs, linewidth=1.5, color="c", label="Counter-rotating") plt.rgrids(np.arange(0.1, 1.1 * max(counter_A_abs), 0.3), angle=180) plt.legend(loc=(0.7, 1), prop={'size': 12}) plt.tight_layout(pad=1.0, w_pad=4) plt.show() return None
def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'): #def subplot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'): num_of_picks=9 theta = radar_factory(len(spoke_labels), frame='circle') fig = plt.figure(figsize=(num_of_picks, num_of_picks)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) num_col=np.floor(np.sqrt(len(data))) num_row=np.ceil(num_of_picks/num_col) for k,(data_col,sensor_label_) in enumerate(zip(data,sensor_labels)): #subplot(num_col,num_row,i+1) ax = fig.add_subplot(num_col,num_row,k+1, projection="radar") ax.plot(theta, data_col) ax.fill(theta, data_col, alpha=0.2) ax.set_varlabels(spoke_labels) #plt.title(sensor_label_,fontsize='small') legend = plt.legend([sensor_label_], loc=(-0.2, 1.1), labelspacing=0.01) plt.setp(legend.get_texts(), fontsize='small') radar_bnd=max(max(data)) #import pdb;pdb.set_trace() rgrid_spacing=np.round(list(np.arange(0.1,radar_bnd,float(radar_bnd)/5)),2) plt.rgrids(rgrid_spacing) #plt.rgrids([0.1 + 2*i / 10.0 for i in range(radar_bnd)]) ##radar_chart.plot(data_col, spoke_labels, sensor_label_, saveto="time_radar.png",frame_type='circle') if saveto != None: plt.savefig(saveto)
def radar_plot(): """ radar plot """ # 生成测试数据 labels = np.array(["A", "B", "C", "D", "E", "F"]) data = np.array([38, 43, 90, 67, 89, 73]) theta = np.linspace(0, 2 * np.pi, len(data), endpoint=False) # 数据预处理 data = np.concatenate((data, [data[0]])) theta = np.concatenate((theta, [theta[0]])) # 画图方式 plt.subplot(111, polar=True) # 设置"theta grid"/"radar grid" plt.thetagrids(theta * (180 / np.pi), labels=labels) plt.rgrids(np.arange(20, 101, 20), labels=np.arange(20, 101, 20), angle=0) plt.ylim(0, 100) # 画雷达图,并填充雷达图内部区域 plt.plot(theta, data, "bo-", linewidth=2) plt.fill(theta, data, color="red", alpha=0.25) # 图形显示 plt.show() return
def radar_plot(): """ radar plot """ # 生成测试数据 labels = np.array(["A组", "B组", "C组", "D组", "E组", "F组"]) data = np.array([68, 83, 90, 77, 89, 73]) theta = np.linspace(0, 2 * np.pi, len(data), endpoint=False) # 数据预处理 data = np.concatenate((data, [data[0]])) theta = np.concatenate((theta, [theta[0]])) # 画图方式 plt.subplot(111, polar=True) plt.title("雷达图", fontproperties=myfont) # 设置"theta grid"/"radar grid" plt.thetagrids(theta * (180 / np.pi), labels=labels, fontproperties=myfont) plt.rgrids(np.arange(20, 100, 20), labels=np.arange(20, 100, 20), angle=0) plt.ylim(0, 100) # 画雷达图,并填充雷达图内部区域 plt.plot(theta, data, "bo-", linewidth=2) plt.fill(theta, data, color="red", alpha=0.25) # 图形显示 plt.show() return
def create_plot(): N = 9 theta = radar_factory(N, frame='circle') data = example_data() spoke_labels = data.pop(0) fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) colors = ['b', 'r', 'g', 'm', 'y'] # Plot the four cases from the example data on separate axes for n, (title, case_data) in enumerate(data): ax = fig.add_subplot(2, 2, n + 1, projection='radar') plt.rgrids([0.2, 0.4, 0.6, 0.8]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(case_data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) # add legend relative to top-left plot plt.subplot(2, 2, 1) labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5') legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1) plt.setp(legend.get_texts(), fontsize='small') plt.figtext(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios', ha='center', color='black', weight='bold', size='large') plt.show()
def request_radar_plot(request, pname): N = 10 theta = radar_factory(N, frame='polygon') data = fetch_data(pname) spoke_labels = data.pop(0) fig = plt.figure(figsize=(14, 14)) colors = ['b', 'r'] for n, (title, case_data) in enumerate(data): ax = fig.add_subplot(1, 1, 1, projection='radar') plt.rgrids([10, 20, 30, 40]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(case_data, colors): d = np.array(d) ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) plt.subplot(1, 1, 1) labels = ('Statistics', 'MaxKDA') legend = plt.legend(labels, loc=(0.90, .95), labelspacing=0.2) plt.setp(legend.get_texts(), fontsize='small') fig.set_facecolor('white') canvas = FigureCanvas(fig) response = HttpResponse(content_type='image/png') canvas.print_png(response) return response
def plot(self, legend=True, fig_title=None): theta = radar_factory(self.get_data_size(), frame='polygon') fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) colors = ['b', 'r', 'g', 'm', 'y'] # Plot the four cases from the example data on separate axes for n, title in enumerate(self._data.keys()): ax = fig.add_subplot(2, 2, n + 1, projection='radar') plt.rgrids([0.02, 0.04, 0.06, 0.08]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(self._data[title], colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(self._labels) if legend: self.plot_legend() if fig_title is not None: self.plot_title(fig_title) plt.show()
def buildRadar(data, name): N = 7 theta = radar_factory(N, frame="polygon") spoke_labels = data.pop(0) fig = plt.figure(figsize=(7, 7)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) colors = ["b", "r", "g", "m", "y"] # Plot the four cases from the example data on separate axes for n, (title, case_data) in enumerate(data): ax = fig.add_subplot(2, 2, n + 1, projection="radar") plt.rgrids([0.2, 0.4, 0.6, 0.8]) ax.set_title( title, weight="bold", size="medium", position=(0.5, 1.1), horizontalalignment="center", verticalalignment="center", ) for d, color in zip(case_data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) # add legend relative to top-left plot plt.subplot(2, 2, 1) labels = ("Factor 1", "Factor 2", "Factor 3", "Factor 4", "Factor 5") plt.figtext(0.5, 0.965, "TITLE", ha="center", color="black", weight="bold", size="large") savefig(name) plt.clf()
def create_polar_plot(sim_group, sim_id, outfile_idx, r_min=0.2, r_max=5.0, tick_step_size=0.2): fig = plt.figure(figsize=(10, 10)) ax = plt.subplot(polar=True) plotting.gas_density.polar_2D(ax, sim_group, sim_id, outfile_idx, r_max_crop=1.4) save_loc = os.path.join(FIGURE_DIR, sim_group, sim_id, f'polar_{outfile_idx}.png') plt.grid(True, color='black') # ticks = np.arange(r_min, r_max, tick_step_size) ticks = list(np.arange(0.5, 5.5, 1)) plt.yticks(ticks, size=20) plt.rgrids(ticks) plt.plot(np.linspace(0, 2 * np.pi, 100), [0.2] * 100, color='black', linewidth=1) ax.set_rlabel_position(90) if sim_id.startswith('10') or outfile_idx == 50: cb = plt.colorbar(fraction=0.046, pad=0.04) cb.ax.tick_params(labelsize=20) if sim_id not in os.listdir(os.path.join(FIGURE_DIR, sim_group)): os.mkdir(os.path.join(FIGURE_DIR, sim_group, sim_id)) plt.savefig(save_loc)
def initialisation_graphe(ondes,enonce=True): plt.clf() # Nettoyage, on commence un nouveau graphe plt.axes(polar=True) # On initie un graphe en polaires # Puis on définit le titre if enonce: titre = 'Enonce: Sommer ' else : titre = 'Corrige: Sommer ' titre += ", ".join(['${}$'.format(o) for o in ondes[:-1]]) titre += " et ${}$.".format(ondes[-1]) plt.title(titre) # et finalement les grilles en distances plt.rgrids([i+1 for i in range(max_size)]) plt.thetagrids([i*15 for i in range(360//15)]) # et en angles
def overlaid_plot(terms, ICA_component_number, savepath=None, filtered_num=False): """ Args: - ICA_component_number: integer that corresponds to ICA analysis and directory - savepath: just shows if no path is provided - filtered_num: Integer that corresponds to the number of terms desired in the radar plot. """ ICA_path = '/Volumes/Huettel/KBE.01/Analysis/Neurosynth/ICA/ICA%s' %ICA_component_number big_list = get_all_term_weights(terms, ICA_path) if filtered_num: big_list = term_weight_filter(big_list, filtered_num) N = filtered_num else: N = ICA_component_number data = convert_final_data(big_list) theta = radar_factory(N, frame='polygon') spoke_labels = data.pop('column names') fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) colors = ['b', 'r', 'g', 'y', 'm'] # Plot the four cases from the example data on separate axes for n, title in enumerate(data.keys()): ax = fig.add_subplot(1, 1, n+1, projection='radar') plt.rgrids([2, 4, 6, 8]) #plt.rgrids([0.2, 0.4, 0.6, 0.8]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(data[title], colors): ax.set_ylim(0,10) ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) # add legend relative to top-left plot plt.subplot(1, 1, 1) labels = tuple(terms) legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1) plt.setp(legend.get_texts(), fontsize='large') plt.figtext(0.5, 0.965, '', ha='center', color='black', weight='bold', size='large') if savepath == None: plt.show() else: plt.savefig(savepath)
def add_axis(self, fig, subplot): ax = fig.add_subplot(subplot, polar=True) # Set up ticks and labels self.r_ticks = range(self.r0, self.r0 + (self.nrange+1) * self.dr, self.dr) self.theta_ticks = [self.theta0 + self.dtheta * b for b in range(self.nbeam+1)] rlabels = [""] * len(self.r_ticks) for i in range(0, len(rlabels), 5): rlabels[i] = i plt.rgrids(self.r_ticks, rlabels) plt.thetagrids(self.theta_ticks, range(self.nbeam)) return ax
def draw_radar(weapons, color_cluster, fitness_cluster, num_samples): N = 10 theta = radar_factory(N, frame='polygon') data = get_data(weapons) spoke_labels = data.pop('column names') fig = plt.figure(figsize=(16, 9)) fig.subplots_adjust(wspace=0.50, hspace=0.25) colors = ['b', 'r', 'g', 'm', 'y'] weapons = data['Weapon1'], data['Weapon2'] for i in range(len(weapons)) : ax = fig.add_subplot(2, 3, i+1, projection='radar') plt.rgrids([0.5], ('')) ax.set_title("Weapon" + str(i+1), weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') ax.plot(theta, weapons[i], color=color_cluster) ax.fill(theta, weapons[i], facecolor=color_cluster, alpha=0.25) ax.set_varlabels(spoke_labels) ax = fig.add_subplot(2, 3, 4) plt.ylim(0, 3) ax.set_title("Balance") ax.boxplot( [fitness_cluster[i][0] for i in range(len(fitness_cluster))] ) ax = fig.add_subplot(2, 3, 5) plt.ylim(0, 2500) ax.set_title("Distance") ax.boxplot( [fitness_cluster[i][1] for i in range(len(fitness_cluster))] ) ax = fig.add_subplot(2, 3, 6) plt.ylim(0, 20) ax.set_title("Kill Streak") ax.boxplot( [fitness_cluster[i][2] for i in range(len(fitness_cluster))] ) # add legend relative to top-left plot ''' plt.subplot(2, 2, 1) labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5') legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1) plt.setp(legend.get_texts(), fontsize='small') ''' plt.figtext(0.5, 0.965, 'Mean of clustered weapon, samples = ' + str(num_samples), ha='center', color='black', weight='bold', size='large')
def create_figure(all_data): # takes in data and title and creates and saves plot width = 0.45 # width of the bars (in radians) # create the figure, dont change fig = plt.figure() ax = fig.add_subplot(111, polar=True) # angle positions, 0 to 360 with increments of 360/5 xo = list(range(0, 360, 360 / 5)) # Convert to radians and subtract half the width # of a bar to center it. x = [i * pi / 180 for i in xo] # set the labels for each bar, do not change ax.set_xticks(x) ax.set_xticklabels(['Military\nProwess', 'Productivity', 'Resource', 'Self-\nSufficiency', 'Morale']) ax.set_thetagrids(xo, frac=1.15) # frac changes distance of label from circumference of circle plt.ylim(0, 100) # sets range for radial grid fig.suptitle("India \n1993-2012", fontsize=20, y=0.5, x=0.1) # title of plot plt.rgrids([20, 40, 60, 80, 100], angle=33, fontsize=10) # the numbers you see along radius, angle changes position colorList = []; count = -1 for key in all_data: count = count + 1 data = all_data[key] mylist = [item+0.5*(count-len(all_data)/2)/len(all_data) for item in x] bars = ax.bar(mylist, data, width=width, align='center') # do the plotting i = 0 for r, bar in zip(data, bars): bar.set_facecolor( cm.jet(0.8*count/len(all_data))) # set color for each bar, intensity proportional to height of bar colorList.append(cm.jet(0.8*count/len(all_data))) #bar.set_alpha(0.2) # make color partly transparent height = bar.get_height() # this is basically the radial height, or radius of bar # write value of each bar inside it # first param is angle, second is radius -10 makes it go inside the bar if i == 3 and count == 0: ax.text(mylist[i]-width/4*3, height+5, key, ha='center', va='center', fontsize=11) if i == 3 and count == len(all_data)-1: ax.text(mylist[i]+width/4*3, height-5, key, ha='center', va='center', fontsize=11) i = i + 1 plt.savefig('examples/multiple.png')
def radar_sglv(data, labels, title, rand=False): # Plot the four cases from the example data on separate axes N, M = labels.shape j = 0 theta = radar_factory(M, frame='polygon') color = ['red', 'blue', 'green', 'grey'] for w in range(ceil(N / 4)): c = 0 fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) for row in data[4 * w:min(4 * w + 4, N), ::]: index = np.arange(M) if rand: random.shuffle(index) ax = fig.add_subplot(2, 2, c + 1, projection='radar') ax.set_title('Singular Value n°' + str(j + 1), weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') ax.plot(theta, row[index], color=color[c]) ax.fill(theta, row[index], facecolor=color[c], alpha=0.25) ax.set_varlabels(labels[j, index]) plt.rgrids([0.2, 0.4, 0.6, 0.8]) c = c + 1 j = j + 1 # add legend relative to top-left plot plt.subplot(2, 2, 1) #label = ('Singular Value n°'+ str(4*w), 'Singular Value n°'+str(4*(w+1)), # 'Singular Value n°'+ str(4*(w+2)), 'Singular Value n°'+str(4*(w+3))) #legend = plt.legend(label, loc=(0.9, .95), labelspacing=0.1) #@plt.setp(legend.get_texts(), fontsize='small') plt.figtext(0.5, 0.965, title, ha='center', color='black', weight='bold', size='large') plt.show()
def plot_hsi_image(self, show_plot=True): plt.subplot(221) plt.gray() plt.imshow(self.hsi_image[:, :, 0] / (2 * 3.14) * 255., interpolation='nearest') plt.axis('off') plt.subplot(222, projection='polar') plt.gray() azi = self.hsi_image[:, :, 0] / (2 * 3.14) * 360. azi = azi.flatten() azi = list(azi) azi.append(359.) azi = np.array(azi) z = np.cos(np.radians(azi / 2.)) coll = rose_graph.rose(azi, z=z, bidirectional=False, bins=50) plt.xticks(np.radians(range(0, 360, 10)), [ 'Red', '', '', 'Red-Magenta', '', '', 'Magenta', '', '', 'Magenta-Blue', '', '', 'Blue', '', '', 'Blue-Cyan', '', '', 'Cyan', '', '', 'Cyan-Green', '', '', 'Green', '', '', 'Green-Yellow', '', '', 'Yellow', '', '', 'Yellow-Red', '', '' ]) plt.colorbar(coll, orientation='horizontal') plt.xlabel('A rose diagram colored by a second variable') plt.rgrids(range(5, 20, 5), angle=360) plt.subplot(223) plt.imshow(self.hsi_image[:, :, 0] / (2 * 3.14) * 255., cmap=matplotlib.cm.hsv) plt.axis('off') plt.subplot(224) data = self.hsi_image[:, :, 0] / (2 * 3.14) * 255. data = data.flatten() data = list(data) data.append(359.) n, bins, patches = plt.hist(data, 36) bin_centers = 0.5 * (bins[:-1] + bins[1:]) col = bin_centers col /= 360 col = col print bins for c, p in zip(col, patches): plt.setp(p, 'facecolor', matplotlib.cm.hsv(c)) plt.xticks([np.ceil(x) for i, x in enumerate(bins) if i % 3 == 0]) if show_plot: plt.show()
def __init__(self, rrre_class, elective_class, filename): self.filename = filename plt.cla() self.rrre_class = rrre_class self.elective_class = elective_class N = len(rrre_class.grade_dict) theta = self.radar_factory(N, frame='polygon') data = self.example_data() spoke_labels = data.pop(0) fig = plt.figure(figsize=(9, 9)) #fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) colors = [ '#90EE90', '#4F4F4F', '#00FF00', '#00FFFF', '#FF7256', '#FFA500', '#8B7E66', '#FF8247' ] # Plot the four cases from the example data on separate axes for n, (title, case_data) in enumerate(data): ax = fig.add_subplot(1, 1, n + 1, projection='radar') if rrre_class.biggest <= 4: plt.rgrids([1, 2, 3, 4]) elif rrre_class.biggest <= 8: plt.rgrids([2, 4, 6, 8]) elif rrre_class.biggest <= 12: plt.rgrids([3, 6, 9, 12]) else: plt.rgrids([4, 8, 13, 17]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center', fontproperties=zhfont) for d, color in zip(case_data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) # add legend relative to top-left plot #plt.subplot(2, 2, 1) labels = [ semester_list[3] for semester_list in self.rrre_class.SEMESTERS_LIST ] legend = plt.legend(labels, loc=(0.52, .88), labelspacing=0.1, prop=zhfont) #plt.setp(legend.get_texts(), fontsize='small') #plt.figtext(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',ha='center', color='black', weight='bold', size='large') self.loc = str(self.elective_class.message_list[0] ) + '/' + self.filename + '_2.png' plt.savefig('/var/www/html/szx/' + self.loc, bbox_inches='tight')
def test_polar_wrap(): D2R = np.pi / 180.0 fig = plt.figure() plt.subplot( 111, polar=True, resolution=1 ) plt.polar( [179*D2R, -179*D2R], [0.2, 0.1], "b.-" ) plt.polar( [179*D2R, 181*D2R], [0.2, 0.1], "g.-" ) plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] ) fig.savefig( 'polar_wrap_180' ) fig = plt.figure() plt.subplot( 111, polar=True, resolution=1 ) plt.polar( [2*D2R, -2*D2R], [0.2, 0.1], "b.-" ) plt.polar( [2*D2R, 358*D2R], [0.2, 0.1], "g.-" ) plt.polar( [358*D2R, 2*D2R], [0.2, 0.1], "r.-" ) plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] ) fig.savefig( 'polar_wrap_360' )
def main(): azi = wd_11_12 z = ws_11_12 plt.figure(figsize=(5,6)) plt.subplot(111, projection='polar') coll = rose(azi, z=z, bidirectional=True) plt.xticks(np.radians(range(0, 360, 45)), ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']) plt.colorbar(coll, orientation='horizontal') plt.xlabel('2011 - 2012 3m Wind rose colored by mean wind speed') plt.rgrids(range(5, 20, 5), angle=290) plt.savefig('/home/cparr/Snow_Patterns/figures/wind/winter_11_12.png',dpi = 300) plt.show()
def flowers(n): a=[4,5,6,7,0.75,2.5,3.5,5.0/3.0,7.0/3.0,7.0/4.0,1.0/6.0,1.0/8.0,1.0/7.0,2.0/9.0] if a[n-1]>=4: b='yellow' elif a[n-1]<=1: b='red' else: b='magenta' pyplot.axes(polar=True) pyplot.thetagrids([]) pyplot.rgrids([2]) theta = arange(-9, 9, 1./180)*pi # angular coordinates figure(1) pyplot.plot(theta, cos(a[n-1]*theta), color=b, linewidth=5) # drawing the polar rose show() return
def plotSpeedBear(self, sAllData, bAllData): """ Plot speed and bearing against each other """ plt.figure(self.figurenum(), figsize=(7, 7)) plt.subplot(111) ii = np.where((sAllData < sys.maxsize) & (bAllData < sys.maxsize)) plt.polar((np.pi / 2. - np.radians(bAllData[ii])), sAllData[ii], 'k.', markersize=2) thetalabels = (90 - np.arange(0, 360, 45)) ii = np.where(thetalabels < 0) thetalabels[ii] += 360 lines, labels = plt.rgrids(np.arange(20., 101., 20.), labels=None, angle=67.5) lines, labels = plt.thetagrids(np.arange(0., 360., 45.), thetalabels) plt.ylim(0, 100.) plt.grid(True) r = np.corrcoef(bAllData[ii], sAllData[ii])[1, 0] plt.text(45, 125, "r = %5.3f" % r, ha='center', va='center', color='r', size=14) plt.title("Speed vs bearing") self.savefig('spd_bear_corr')
def _open_figure(self): # Create axis self.fig = plt.figure(figsize=(12, 9)) self.ax = self.fig.add_subplot(111, polar=True) # Set up ticks and labels self.r_ticks = range(self.r0, self.r0 + (self.nrange + 1) * self.dr, self.dr) self.theta_ticks = [ self.theta0 + self.dtheta * b for b in range(self.nbeam + 1) ] rlabels = [""] * len(self.r_ticks) for i in range(0, len(rlabels), 5): rlabels[i] = i plt.rgrids(self.r_ticks, rlabels) plt.thetagrids(self.theta_ticks, range(self.nbeam))
def plot_phaseplot_l(dictdata, keys, autok, title, withn='yes'): """Plots a phase plot where the radius is not fixed to 1.""" colors = ['r', 'b', 'g', 'y', 'k'] plt.suptitle(title, fontsize='large' ) if autok == 'yes': k = dictdata.keys() for i, condition in enumerate(keys): datac = colors[i] data = dictdata[condition] try: n = len(data) theta, r = zip(*data) except TypeError: theta, r = data n = 1 if withn == 'yes': plt.polar(theta, r, 'o', color=datac, label=condition + '\n n=' + str(n)) if withn == 'no': plt.polar(theta, r, 'o', color=datac, label=condition) lines, labels = plt.rgrids( (1.0, 1.4), ('', ''), angle=0 ) tlines, tlabels = plt.thetagrids( (0, 90, 180, 270), ('0', 'pi/2', 'pi', '3pi/2') ) leg = plt.legend(loc=(0.93,0.8)) for t in leg.get_texts(): t.set_fontsize('small') plt.subplots_adjust(top=0.85) plt.draw()
def polar_axis(): theta = np.arange(0, 2 * np.pi, 0.02) plt.subplot(121, polar=True) plt.plot(theta, 1.6 * np.ones_like(theta), lw=2) plt.plot(3 * theta, theta / 3, '--', lw=2) plt.plot(theta, 1.4 * np.cos(5 * theta), '--', color='green', lw=2) plt.plot(theta, 1.8 * np.cos(4 * theta), lw=2) # 设置同心圆栅格的大小和文字标准的角度 plt.rgrids(np.arange(0.5, 2, 0.5), angle=45) # 设置放射线栅格的角度 plt.thetagrids([0, 45]) plt.show()
def makeSpiderChart(jobID, savedLengths, outputDir): #setting up the directory to save the chart in cwd = os.getcwd() prefix = "".join([cwd,'/',jobID,'_SignificantWords.png']) #local variables data = [] labels = [] largestWords = 0 #assiging values to lists for the spider chart for key, value in savedLengths.items(): data.append(value) labels.append(key) if value > largestWords: largestWords = value N = len(labels) theta = radar_factory(N, frame='circle') spoke_labels = labels #size of the file fig = plt.figure(figsize=(13, 13)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) color = 'b' # Plot the four cases from the example data on separate axes ax = fig.add_subplot(2, 2, 1, projection='radar') plt.rgrids([1, (largestWords*0.25), (largestWords*0.5), (largestWords*0.75), largestWords]) ax.set_title(jobID, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') ax.plot(theta, data, color) ax.fill(theta, data, color, alpha=0.25) ax.set_varlabels(spoke_labels) # add legend relative to top-left plot plt.subplot(2, 2, 1) labels = ('Significant Words', 'Fill') legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1) plt.setp(legend.get_texts(), fontsize='small') plt.figtext(0.5, 0.965, 'Significant Words for Interesting Word Lengths', ha='center', color='black', weight='bold', size='large') savefig(prefix) shutil.move(prefix, outputDir)
def refresh(self, t): # print "refresh radarmap " + str(t) N = 4 theta = radar_factory(N, frame='circle') data = self.pick_data(t) spoke_labels = data.pop(0) self.fig = plt.figure() self.fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.95, bottom=0.05) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) colors = ['r', 'g', 'm', 'y', 'b'] # Plot the four cases from the example data on separate axes for n, (title, case_data) in enumerate(data): ax = self.fig.add_subplot(1, 2, n + 1, projection='radar') plt.rgrids([0.2, 0.4, 0.6, 0.8]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(case_data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) # add legend relative to top-left plot plt.subplot(1, 2, 1) labels = ('Cell 1', 'Cell 2', 'Cell 3', 'Cell 4') legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1) plt.setp(legend.get_texts(), fontsize='small') plt.figtext(0.5, 0.965, 'Feature Snapshots Panel', ha='center', color='black', weight='bold', size='large')
def plot(data, spoke_labels, sensor_labels,saveto=None,frame_type='polygon'): theta = radar_factory(len(spoke_labels), frame=frame_type) fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) ax = fig.add_subplot(111, projection="radar") plt.rgrids([np.round(0.1 + i / 10.0,2) for i in range(10)]) for d in data: ax.plot(theta, d) ax.fill(theta, d, alpha=0.2) ax.set_varlabels(spoke_labels) legend = plt.legend(sensor_labels, loc=(0.0, 0.9), labelspacing=0.1) plt.setp(legend.get_texts(), fontsize='small') if saveto != None: plt.savefig(saveto)
def main(): azi = np.random.uniform(0, 180, 100000) azi = azi.tolist() azi.append(359.) azi = np.array(azi) z = np.cos(np.radians(azi / 2.)) plt.figure(figsize=(5, 6)) plt.subplot(111, projection='polar') coll = rose(azi, z=z, bidirectional=False) plt.xticks(np.radians(range(0, 360, 45)), ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']) plt.colorbar(coll, orientation='horizontal') plt.xlabel('A rose diagram colored by a second variable') plt.rgrids(range(5, 20, 5), angle=360) plt.show()
def plot_hsi_image(self, show_plot=True): plt.subplot(221) plt.gray() plt.imshow(self.hsi_image[:, :, 0] / (2 * 3.14) * 255., interpolation='nearest') plt.axis('off') plt.subplot(222, projection='polar') plt.gray() azi = self.hsi_image[:, :, 0] / (2 * 3.14) * 360. azi = azi.flatten() azi = list(azi) azi.append(359.) azi = np.array(azi) z = np.cos(np.radians(azi / 2.)) coll = rose_graph.rose(azi, z=z, bidirectional=False, bins=50) plt.xticks(np.radians(range(0, 360, 10)), ['Red', '', '', 'Red-Magenta', '', '', 'Magenta', '', '', 'Magenta-Blue', '', '', 'Blue', '', '', 'Blue-Cyan', '', '', 'Cyan', '', '', 'Cyan-Green', '', '', 'Green', '', '', 'Green-Yellow', '', '', 'Yellow', '', '', 'Yellow-Red', '', '']) plt.colorbar(coll, orientation='horizontal') plt.xlabel('A rose diagram colored by a second variable') plt.rgrids(range(5, 20, 5), angle=360) plt.subplot(223) plt.imshow(self.hsi_image[:, :, 0] / (2 * 3.14) * 255., cmap=matplotlib.cm.hsv) plt.axis('off') plt.subplot(224) data = self.hsi_image[:, :, 0] / (2 * 3.14) * 255. data = data.flatten() data = list(data) data.append(359.) n, bins, patches = plt.hist(data, 36) bin_centers = 0.5 * (bins[:-1] + bins[1:]) col = bin_centers col /= 360 col = col print bins for c, p in zip(col, patches): plt.setp(p, 'facecolor', matplotlib.cm.hsv(c)) plt.xticks([np.ceil(x) for i, x in enumerate(bins) if i % 3 == 0]) if show_plot: plt.show()
def plotDecisionErrors(): N = 8 theta = radar_factory(N, frame='polygon') data = getDecisionErrorData() spoke_labels = data.pop(0) fig = plt.figure(figsize=(9, 9)) fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05) fig.text(0.1, 0.425, 'DE1: Too Fast for Conditions') fig.text(0.1, 0.40, 'DE2: Too Fast for Curve') fig.text(0.1, 0.375, 'DE3: False Assumption of Other\'s Action') fig.text(0.1, 0.35, 'DE4: Illegal Maneuver') fig.text(0.1, 0.325, 'DE5: Misjudgment of Gap or Other\'s Speed') fig.text(0.1, 0.30, 'DE6: Following Too Closely') fig.text(0.1, 0.275, 'DE7: Aggressive Driving Behavior') fig.text(0.1, 0.25, 'DE8: Unknown Decision Error') # colors = ['b', 'r', 'g', 'm', 'y'] colors = ['b', 'r'] # Plot the four cases from the example data on separate axes for n, (title, case_data) in enumerate(data): ax = fig.add_subplot(2, 2, n + 1, projection='radar') plt.rgrids([5, 10, 15, 20, 25, 30]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(case_data, colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) # add legend relative to top-left plot ## plt.subplot(2, 2, 1) ## labels = ('Conventional Vehicles', 'Vehicles with Cognition') ## legend = plt.legend(labels, loc=(-0.1, -0.3), labelspacing=0.1) ## plt.setp(legend.get_texts(), fontsize='small') # plt.figtext(0.5, 0.965, 'Comparison of Critical Reasons for Pre-Crash Events', # ha='center', color='black', weight='bold', size='large') plt.show()
def test_polar_wrap(): D2R = np.pi / 180.0 fig = plt.figure() plt.subplot(111, polar=True) plt.polar( [179*D2R, -179*D2R], [0.2, 0.1], "b.-" ) plt.polar( [179*D2R, 181*D2R], [0.2, 0.1], "g.-" ) plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] ) assert len(fig.axes) == 1, 'More than one polar axes created.' fig = plt.figure() plt.subplot( 111, polar=True) plt.polar( [2*D2R, -2*D2R], [0.2, 0.1], "b.-" ) plt.polar( [2*D2R, 358*D2R], [0.2, 0.1], "g.-" ) plt.polar( [358*D2R, 2*D2R], [0.2, 0.1], "r.-" ) plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )
def test_polar_wrap(): D2R = np.pi / 180.0 fig = plt.figure() plt.subplot(111, polar=True) plt.polar([179 * D2R, -179 * D2R], [0.2, 0.1], "b.-") plt.polar([179 * D2R, 181 * D2R], [0.2, 0.1], "g.-") plt.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3]) assert len(fig.axes) == 1, 'More than one polar axes created.' fig = plt.figure() plt.subplot(111, polar=True) plt.polar([2 * D2R, -2 * D2R], [0.2, 0.1], "b.-") plt.polar([2 * D2R, 358 * D2R], [0.2, 0.1], "g.-") plt.polar([358 * D2R, 2 * D2R], [0.2, 0.1], "r.-") plt.rgrids([0.05, 0.1, 0.15, 0.2, 0.25, 0.3])
def display_climate(geography, year, tempdata, raindata): #Create figure and polar axis fig = plt.figure(facecolor='white', figsize=(8,8)) ax = fig.add_subplot(111, polar = True, frameon=False) mintemp=-30 maxtemp=40 ax.text(0,mintemp, geography.upper(), color='#555555', horizontalalignment='center', verticalalignment='center', size=30) ax.text(0,maxtemp+1, str(year), color='#555555', horizontalalignment='center', size=14) #Min/Max temps as bars for i,(tmin,tmax,tmean) in enumerate(tempdata): if np.abs(tmax-tmin)<1: tmin=tmin-0.5 tmax=tmax+0.5 ax.plot([2*np.pi*i/365.0]*2, [tmin,tmax], color=cm.spectral((tmean+5)/45.0), linewidth=1.5, alpha=0.6); # plot rainfall as scatters ax.scatter([2*np.pi*r/365. for r in raindata['rainydays']], raindata['tcenters'], s=[100*r for r in raindata['rainfalls']], alpha=0.5, facecolor='#99aacc', linewidth=0) # tweak ranges and orientation of polar plot ax.set_rmax(maxtemp) ax.set_rmin(mintemp) ax.set_theta_direction(-1) ax.set_theta_zero_location("N") #Tweak polar axes, gridding, labels ax.tick_params(axis='both', colors='#b0b0b0') ax.set_xticks([m*2*np.pi/12 for m in range(12)]) months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'] ax.set_xticklabels( months, fontsize=10 ) ax.get_xaxis().grid(False) plt.rgrids( (0.01, 10, 20, 30, 40), labels=('0 C', '', '20 C', '', '40 C' ), angle=180) # radii only positive here, but override later ax.get_yaxis().grid(which='minor',linestyle='-',color='#bbbbbb', alpha=0.3) ax.get_yaxis().grid(which='major',linestyle='-',color='#bbbbbb', alpha=0.4, linewidth=1.4) ax.set_yticks([10, 30], minor=True) ax.set_yticks([0, 20, 40]) #ax.set_yticklabels( ['0 $^\circ$C', '20 $^\circ$C', '40 $^\circ$C' ], fontsize=10) ax.set_yticklabels( ['0 C', '20 C', '40 C' ], fontsize=10) plt.show()
def plot_radar(example_data, nVar): N = nVar theta = radar_factory(N, frame='polygon') data = example_data people_Num = len(data) spoke_labels = data.pop('column names') fig = plt.figure(figsize=(9, 2 * people_Num)) fig.subplots_adjust(wspace=0.55, hspace=0.10, top=0.95, bottom=0.05) colors = ['b', 'r', 'g', 'm', 'y'] for n, title in enumerate(data.keys()): ax = fig.add_subplot(int(people_Num / 3) + 1, 3, n + 1, projection='radar') plt.rgrids([0.2, 0.4, 0.6, 0.8]) plt.setp(ax.get_yticklabels(), visible=False) plt.ylim([0, 1]) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), color='b', horizontalalignment='center', verticalalignment='center', fontproperties=zhfont) for d, color in zip(data[title], colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) plt.subplot(int(people_Num / 3) + 1, 3, 1) plt.figtext(0.5, 0.965, '战力统计', fontproperties=zhfont, ha='center', color='black', weight='bold', size='large') plt.show()
def sonar_graph(ping_readings): # force square figure and square axes looks better for polar, IMO fig = figure(figsize=(6,6)) ax = P.subplot(1, 1, 1, projection='polar') P.rgrids([28, 61, 91]) ax.set_theta_zero_location('N') ax.set_theta_direction(-1) theta = 356 angle = theta * np.pi / 180.0 radii = [ping_readings[0]] width = .15 bars1 = ax.bar(0, 100, width=0.001, bottom=0.0) #print "theta, radii, width: ", theta, radii, width bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') theta = 86 angle = theta * np.pi / 180.0 radii = [ping_readings[1]] width = .15 bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') theta = 176 angle = theta * np.pi / 180.0 radii = [ping_readings[2]] width = .15 bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') theta = 266 angle = theta * np.pi / 180.0 radii = [ping_readings[3]] width = .15 bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') pil_img = fig2img(fig) #print type(pil_img), pil_img sonar_image = PILtoCV_4Channel(pil_img) cv.ShowImage("Sonar", sonar_image ) #cv.MoveWindow ('Sonar',50 ,50 ) #time.sleep(.01) cv.WaitKey(10) #garbage cleanup fig.clf() P.close() return sonar_image
def sonar_graph(ping_readings): # force square figure and square axes looks better for polar, IMO fig = figure(figsize=(6, 6)) ax = P.subplot(1, 1, 1, projection='polar') P.rgrids([28, 61, 91]) ax.set_theta_zero_location('N') ax.set_theta_direction(-1) theta = 356 angle = theta * np.pi / 180.0 radii = [ping_readings[0]] width = .15 bars1 = ax.bar(0, 100, width=0.001, bottom=0.0) #print "theta, radii, width: ", theta, radii, width bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') theta = 86 angle = theta * np.pi / 180.0 radii = [ping_readings[1]] width = .15 bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') theta = 176 angle = theta * np.pi / 180.0 radii = [ping_readings[2]] width = .15 bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') theta = 266 angle = theta * np.pi / 180.0 radii = [ping_readings[3]] width = .15 bars = ax.bar(angle, radii, width=width, bottom=0.0, color='blue') pil_img = fig2img(fig) #print type(pil_img), pil_img sonar_image = PILtoCV_4Channel(pil_img) cv.ShowImage("Sonar", sonar_image) #cv.MoveWindow ('Sonar',50 ,50 ) #time.sleep(.01) cv.WaitKey(10) #garbage cleanup fig.clf() P.close() return sonar_image
def display_climate_radial(geography, year, tempdata, raindata): #Create figure and polar axis fig = plt.figure('%s_radial' % geography, facecolor='white', figsize=(8,8)) ax = fig.add_subplot(111, polar = True, frameon=False) mintemp=-30 maxtemp=40 ax.text(0,mintemp, geography.upper(), color='#555555', horizontalalignment='center', size=30) ax.text(0,maxtemp+1, str(year), color='#555555', horizontalalignment='center', size=10) #Min/Max temps as bars for i,(tmin,tmax,tmean) in enumerate(tempdata): if np.abs(tmax-tmin)<1: tmin=tmin-0.5 tmax=tmax+0.5 ax.plot([2*np.pi*i/365.0]*2, [tmin,tmax], color=cm.spectral((tmean+5)/45.0), linewidth=1.5, alpha=0.6); # plot rainfall as scatters ax.scatter([2*np.pi*r/365. for r in raindata['rainydays']], raindata['tcenters'], s=[100*r for r in raindata['rainfalls']], alpha=0.5, facecolor='#99aacc', linewidth=0) # tweak ranges and orientation of polar plot ax.set_rmax(maxtemp) ax.set_rmin(mintemp) ax.set_theta_direction(-1) ax.set_theta_zero_location("N") #Tweak polar axes, gridding, labels ax.tick_params(axis='both', colors='#bbbbbb') ax.set_xticks([m*2*np.pi/12 for m in range(12)]) months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC'] ax.set_xticklabels( months, fontsize=10 ) ax.get_xaxis().grid(False) plt.rgrids( (0.01, 10, 20, 30, 40), labels=('0 C', '', '20 C', '', '40 C' ), angle=180) # radii only positive here, but override later ax.get_yaxis().grid(which='minor',linestyle='-',color='#bbbbbb', alpha=0.3) ax.get_yaxis().grid(which='major',linestyle='-',color='#bbbbbb', alpha=0.4, linewidth=1.4) ax.set_yticks([10, 30], minor=True) ax.set_yticks([0, 20, 40]) ax.set_yticklabels( ['0 C', '20 C', '40 C' ], fontsize=10) plt.show()
def test_polar_wrap(): D2R = np.pi / 180.0 fig = plt.figure() #NOTE: resolution=1 really should be the default plt.subplot( 111, polar=True, resolution=1 ) plt.polar( [179*D2R, -179*D2R], [0.2, 0.1], "b.-" ) plt.polar( [179*D2R, 181*D2R], [0.2, 0.1], "g.-" ) plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] ) fig = plt.figure() #NOTE: resolution=1 really should be the default plt.subplot( 111, polar=True, resolution=1 ) plt.polar( [2*D2R, -2*D2R], [0.2, 0.1], "b.-" ) plt.polar( [2*D2R, 358*D2R], [0.2, 0.1], "g.-" ) plt.polar( [358*D2R, 2*D2R], [0.2, 0.1], "r.-" ) plt.rgrids( [0.05, 0.1, 0.15, 0.2, 0.25, 0.3] )
def subtract(n0,n1): plt.figure() needles2d = np.array([n0,n1,0.]) f = [1.,0.,0.] sn0=signal2d(S0,f,b,d,needles2d,angles2d) f = [0.,1.,0.] sn1=signal2d(S0,f,b,d,needles2d,angles2d) #plt.polar(angles2d,s00,label='fibre at 0') #plt.polar(angles2d,s90,label='fibre at 90') plt.subplot(2,4,1,polar=True) plt.polar(angles2d,(sn0+sn1)/2.,label='mix') lines, labels = plt.rgrids( (20, 40, 60) ) #plt.polar(angles2d,(s00-s90)/2.,label='diff fibres 0 and 90') for (i,theta) in enumerate(np.linspace(-np.pi/2,np.pi/2,7)): plt.subplot(2,4,i+2,polar=True) needles2d = np.array([0.,theta,0.]) f = [0.,1.,0.] stheta=signal2d(S0,f,b,d,needles2d,angles2d) plt.polar(angles2d,(sn0+sn1)/2.-stheta,label=str(-180*theta/np.pi)) lines, labels = plt.rgrids( (20, 40, 60) ) plt.legend(loc='best') plt.suptitle('Subtraction from '+str(180*n0/np.pi)+'+'+str(180*n1/np.pi))
def draw_radar(): N = 10 theta = radar_factory(N, frame='polygon') data = get_data() spoke_labels = data.pop('column names') fig = plt.figure(figsize=(16, 9)) fig.subplots_adjust(wspace=0.50, hspace=0.20) colors = ['b', 'r', 'g', 'm', 'y'] # Plot the four cases from the example data on separate axes for n, title in enumerate(data.keys()): ax = fig.add_subplot(1, 2, n+1, projection='radar') plt.rgrids([0.5], ('')) ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1), horizontalalignment='center', verticalalignment='center') for d, color in zip(data[title], colors): ax.plot(theta, d, color=color) ax.fill(theta, d, facecolor=color, alpha=0.25) ax.set_varlabels(spoke_labels) # add legend relative to top-left plot ''' plt.subplot(2, 2, 1) labels = ('Factor 1') legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1) plt.setp(legend.get_texts(), fontsize='small') ''' plt.figtext(0.5, 0.965, 'Weapons selected', ha='center', color='black', weight='bold', size='large') #plt.show() plt.savefig("flak_vs_rocket.png", bbox_inches='tight', dpi = 200) plt.close()
def draw_radar(weapons, color_cluster, fitness_cluster): N = 10 theta = radar_factory(N, frame='polygon') data = get_data(weapons) spoke_labels = data.pop('column names') fig = plt.figure(figsize=(16, 9)) fig.subplots_adjust(wspace=0.50, hspace=0.25) colors = ['b', 'r', 'g', 'm', 'y'] # Plot the four cases from the example data on separate axes for n, title in enumerate(data.keys()): ax = fig.add_subplot(1, 3, n+1, projection='radar') plt.rgrids([0.5]) for d, color in zip(data[title], colors): ax.plot(theta, d, color=color_cluster) ax.fill(theta, d, facecolor=color_cluster, alpha=0.25) ax.set_varlabels(spoke_labels) ax = fig.add_subplot(1, 3, 3) plt.ylim(0, 3) ax.boxplot(fitness_cluster) # add legend relative to top-left plot ''' plt.subplot(2, 2, 1) labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5') legend = plt.legend(labels, loc=(0.9, .95), labelspacing=0.1) plt.setp(legend.get_texts(), fontsize='small') ''' plt.figtext(0.5, 0.965, 'Mean of clustered weapons', ha='center', color='black', weight='bold', size='large')
def schmidt(name="strike.xlsx", Width=1, Color='k'): if("csv"in name):schmidtraw = pd.read_csv(name) elif("xlsx"in name):schmidtraw = pd.read_excel(name) Data = [] plt.axes(polar=True) plt.polar([0], [90]) plt.xlim((0, 360)) plt.ylim((0, 90)) list1 = [eqar(x) for x in range(0, 90, 15)] list2 = [str(x) for x in range(0, 90, 15)] plt.rgrids(list1, list2) for i in range(len(schmidtraw)): Data.append( [schmidtraw.at[i, "Name"], schmidtraw.at[i, "Strike"], schmidtraw.at[i, "Dip"], schmidtraw.at[i, "Color"], schmidtraw.at[i, "Width"], schmidtraw.at[i, "Alpha"], schmidtraw.at[i, "Marker"]]) S = schmidtraw.at[i, "Strike"] D = schmidtraw.at[i, "Dip"] Width = schmidtraw.at[i, "Width"] Color = schmidtraw.at[i, "Color"] Alpha = schmidtraw.at[i, "Alpha"] Marker = schmidtraw.at[i, "Marker"] plt.plot(np.radians(90 - S), eqar(D), color=Color, linewidth=Width, alpha=Alpha, marker=Marker) plt.plot(120, 30, color='K', linewidth=4, alpha=Alpha, marker='o') plt.thetagrids(range(360 + 90, 0 + 90, -20), [str(x) for x in range(0, 360, 20)]) plt.savefig("Schmidt.png", dpi=600) plt.savefig("Schmidt.svg", dpi=600) plt.show()
def wulf(name="strike.xlsx", Width=1, Color='k'): if("csv"in name):wulfraw = pd.read_csv(name) elif("xlsx"in name):wulfraw = pd.read_excel(name) Data = [] plt.axes(polar=True) plt.polar([0], [90]) plt.xlim((0, 360)) plt.ylim((0, 90)) list1 = [eqan(x) for x in range(0, 90, 15)] list2 = [str(x) for x in range(0, 90, 15)] plt.rgrids(list1, list2) for i in range(len(wulfraw)): Data.append([wulfraw.at[i, "Name"], wulfraw.at[i, "Strike"], wulfraw.at[i, "Dip"], wulfraw.at[i, "Color"], wulfraw.at[i, "Width"], wulfraw.at[i, "Alpha"]]) S = wulfraw.at[i, "Strike"] D = wulfraw.at[i, "Dip"] Width = wulfraw.at[i, "Width"] Color = wulfraw.at[i, "Color"] Alpha = wulfraw.at[i, "Alpha"] r = np.arange(S - 90, S + 91, 1) BearR = [np.radians(-A + 90) for A in r] Line = (eqan(getangular(D, S, r))) plt.plot(BearR, Line, color=Color, linewidth=Width, alpha=Alpha) plt.thetagrids(range(360 + 90, 0 + 90, -20), [str(x) for x in range(0, 360, 20)]) plt.savefig("Wulff.png", dpi=600) plt.savefig("Wulff.svg", dpi=600) plt.show()