def draw_partitioned_graph(G, partition_obj, layout=None, labels=None, layout_type='spring', node_size=70, node_alpha=0.7, cmap=plt.get_cmap('jet'), node_text_size=12, edge_color='blue', edge_alpha=0.5, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # if a premade layout haven't been passed, create a new one if not layout: if graph_type == 'spring': layout = nx.spring_layout(G) elif graph_type == 'spectral': layout = nx.spectral_layout(G) elif graph_type == 'random': layout = nx.random_layout(G) else: layout = nx.shell_layout(G) # prepare the partition list noeds and colors list_nodes, node_color = partition_to_draw(partition_obj) # draw graph nx.draw_networkx_nodes(G, layout, list_nodes, node_size=node_size, alpha=node_alpha, node_color=node_color, cmap=cmap) nx.draw_networkx_edges(G, layout, width=edge_tickness, alpha=edge_alpha, edge_color=edge_color) #nx.draw_networkx_labels(G, layout,font_size=node_text_size, # font_family=text_font) if labels is None: labels = range(len(G)) edge_labels = dict(zip(G, labels)) #nx.draw_networkx_edge_labels(G, layout, edge_labels=edge_labels, # label_pos=edge_text_pos) # show graph plt.axis('off') plt.xlim(0, 1) plt.ylim(0, 1)
def draw_satTrail_multicolor(lons, lats, colormap, Trail_Width=1): ''' 画卫星轨迹,根据colormap使颜色渐变 ''' t = np.linspace(0, len(lons), len(lons)) lons_tmp = [] lats_tmp = [] lon_old = lons[0] ti = 0 for i in xrange(len(lons)): if abs(lons[i] - lon_old) >= 180.: # 轨迹每次过精度180,就分割画一次 points = np.array([lons_tmp, lats_tmp]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection( segments, cmap=plt.get_cmap(colormap), # YlGnBu norm=plt.Normalize(0, len(lons))) lc.set_array(t[ti:i]) lc.set_linewidth(Trail_Width) plt.gca().add_collection(lc) # plt.plot(lons_tmp, lats_tmp, '-', linewidth=Trail_Width, c=color) lons_tmp = [] lats_tmp = [] ti = i lon_old = lons[i] lons_tmp.append(lons[i]) lats_tmp.append(lats[i]) # plt.plot(lons_tmp, lats_tmp, '-', linewidth=Trail_Width, c=color) points = np.array([lons_tmp, lats_tmp]).T.reshape(-1, 1, 2) segments = np.concatenate([points[:-1], points[1:]], axis=1) lc = LineCollection( segments, cmap=plt.get_cmap(colormap), # YlGnBu norm=plt.Normalize(0, len(lons))) lc.set_array(t[ti:i]) lc.set_linewidth(Trail_Width) plt.gca().add_collection(lc)
def draw_partitioned_graph(G, partition_obj, layout=None, labels=None,layout_type='spring', node_size=70, node_alpha=0.7, cmap=plt.get_cmap('jet'), node_text_size=12, edge_color='blue', edge_alpha=0.5, edge_tickness=1, edge_text_pos=0.3, text_font='sans-serif'): # if a premade layout haven't been passed, create a new one if not layout: if graph_type == 'spring': layout=nx.spring_layout(G) elif graph_type == 'spectral': layout=nx.spectral_layout(G) elif graph_type == 'random': layout=nx.random_layout(G) else: layout=nx.shell_layout(G) # prepare the partition list noeds and colors list_nodes, node_color = partition_to_draw(partition_obj) # draw graph nx.draw_networkx_nodes(G,layout,list_nodes,node_size=node_size, alpha=node_alpha, node_color=node_color, cmap = cmap) nx.draw_networkx_edges(G,layout,width=edge_tickness, alpha=edge_alpha,edge_color=edge_color) #nx.draw_networkx_labels(G, layout,font_size=node_text_size, # font_family=text_font) if labels is None: labels = range(len(G)) edge_labels = dict(zip(G, labels)) #nx.draw_networkx_edge_labels(G, layout, edge_labels=edge_labels, # label_pos=edge_text_pos) # show graph plt.axis('off') plt.xlim(0,1) plt.ylim(0,1)
def plot_variable(u, name, direc, cmap=cmaps.parula, scale='lin', numLvls=100, umin=None, umax=None, \ tp=False, \ tpAlpha=1.0, show=False, hide_ax_tick_labels=False, label_axes=True, title='', use_colorbar=True, hide_axis=False, colorbar_loc='right'): """ show -- whether to show the plot on the screen tp -- show triangle cmap -- colors: gist_yarg - grey gnuplot, hsv, gist_ncar jet - typical colors """ mesh = u.function_space().mesh() v = u.compute_vertex_values(mesh) x = mesh.coordinates()[:,0] y = mesh.coordinates()[:,1] t = mesh.cells() if not os.path.isdir( direc ): os.makedirs(direc) full_path = os.path.join(direc, name) if umin != None: vmin = umin else: vmin = v.min() if umax != None: vmax = umax else: vmax = v.max() # countour levels : if scale == 'log': v[v < vmin] = vmin + 1e-12 v[v > vmax] = vmax - 1e-12 from matplotlib.ticker import LogFormatter levels = np.logspace(np.log10(vmin), np.log10(vmax), numLvls) tick_numLvls = min( numLvls, 8 ) tick_levels = np.logspace(np.log10(vmin), np.log10(vmax), tick_numLvls) formatter = LogFormatter(10, labelOnlyBase=False) norm = colors.LogNorm() elif scale == 'lin': v[v < vmin] = vmin + 1e-12 v[v > vmax] = vmax - 1e-12 from matplotlib.ticker import ScalarFormatter levels = np.linspace(vmin, vmax, numLvls) tick_numLvls = min( numLvls, 8 ) tick_levels = np.linspace(vmin, vmax, tick_numLvls) formatter = ScalarFormatter() norm = None elif scale == 'bool': from matplotlib.ticker import ScalarFormatter levels = [0, 1, 2] formatter = ScalarFormatter() norm = None fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(111) c = ax.tricontourf(x, y, t, v, levels=levels, norm=norm, cmap=plt.get_cmap(cmap)) plt.axis('equal') if tp == True: p = ax.triplot(x, y, t, '-', lw=0.2, alpha=tpAlpha) ax.set_xlim([x.min(), x.max()]) ax.set_ylim([y.min(), y.max()]) if label_axes: ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') if hide_ax_tick_labels: ax.set_xticklabels([]) ax.set_yticklabels([]) if hide_axis: plt.axis('off') # include colorbar : if scale != 'bool' and use_colorbar: divider = make_axes_locatable(plt.gca()) cax = divider.append_axes(colorbar_loc, "5%", pad="3%") cbar = plt.colorbar(c, cax=cax, format=formatter, ticks=tick_levels) tit = plt.title(title) if use_colorbar: plt.tight_layout(rect=[.03,.03,0.97,0.97]) else: plt.tight_layout() plt.savefig( full_path + '.eps', dpi=300) if show: plt.show() plt.close(fig)
def plot_const(u, name , direc): if not os.path.isdir( direc ): os.makedirs(direc) full_path = os.path.join(direc, name) full_mesh = os.path.join(direc, 'mesh.svg') mesh = u.function_space().mesh() v = u.compute_vertex_values(mesh) x = mesh.coordinates()[:,0] y = mesh.coordinates()[:,1] t = mesh.cells() vmin = v.min() vmax = v.max() v[v < vmin] = vmin + 1e-12 v[v > vmax] = vmax - 1e-12 numLvls=100 from matplotlib.ticker import ScalarFormatter levels = np.linspace(vmin, vmax, numLvls) tick_numLvls = min( numLvls, 8 ) tick_levels = np.linspace(vmin, vmax, tick_numLvls) formatter = ScalarFormatter() norm = None n = mesh.num_vertices() d = mesh.geometry().dim() # Create the triangulation mesh_coordinates = mesh.coordinates().reshape((n, d)) triangles = np.asarray([cell.entities(0) for cell in cells(mesh)]) triangulation = tri.Triangulation(mesh_coordinates[:, 0], mesh_coordinates[:, 1], triangles) # Plot the mesh # plt.figure() # plt.triplot(triangulation) # plt.savefig( full_mesh ) # Plot of scalar field V = u.function_space() #FunctionSpace(mesh, 'CG', 2) #f_exp = Expression('sin(2*pi*(x[0]*x[0]+x[1]*x[1]))') #f = interpolate(f_exp, V) fig = plt.figure(figsize=(5,5)) ax = fig.add_subplot(111) # Get the z values for each vertex # cmap = plt.cm.jet cmap = cmaps.parula c = ax.tricontourf(x, y, t, v, levels=levels, norm=norm, cmap=plt.get_cmap(cmap)) plt.ioff() #fig = plt.figure() z = np.asarray([u(point) for point in mesh_coordinates]) plt.tripcolor(triangulation, z, cmap=cmap) # alt plt.tricontourf(...) plt.colorbar() # plt.savefig( full_path, bbox_inches='tight' ) plt.savefig( full_path + '.eps', dpi=300) plt.close( fig )
ax1.legend(legend, loc='upper left') ax1.set_title('5Y5Y X-Market') # Correlation Plot #ax2 = sns.heatmap(df_5y5y.corr(), xticklabels=legend, yticklabels=legend, cmap='RdYlGn', center=0, annot=True) spread = df['PLN 5Y X 5Y Fwd Swap Rate'] - avg_5y5y ax2.plot(spread) # Decorations #ax2.title('Historical Correlations', fontsize=22) #ax2.xticks(fontsize=8) #ax2.yticks(fontsize=4) print(df_5y5y.corr()) x1 = avg_5y5y y1 = df_5y5y['PLN 5Y X 5Y Fwd Swap Rate'] ax4 = sns.regplot(x=x1, y=y1, marker="+") #plt.show() colors = np.linspace(0.1, 1, len(df_5y5y)) mymap = plt.get_cmap("winter") ax3 = ax3.scatter(x1, y1, c=colors, cmap=mymap, lw=0) cb = plt.colorbar(ax3) #plt.subplot(x1[-1],y1[-1],'ro') cb.ax.set_yticklabels( [str(p.date()) for p in df_5y5y[::len(df_5y5y) // 10].index]) fig.tight_layout() plt.show()
def plot_variable(u, name, direc, cmap='gist_yarg', scale='lin', numLvls=12, umin=None, umax=None, tp=False, tpAlpha=0.5, show=True, hide_ax_tick_labels=False, label_axes=True, title='', use_colorbar=True, hide_axis=False, colorbar_loc='right'): """ """ mesh = u.function_space().mesh() v = u.compute_vertex_values(mesh) x = mesh.coordinates()[:, 0] y = mesh.coordinates()[:, 1] t = mesh.cells() d = os.path.dirname(direc) if not os.path.exists(d): os.makedirs(d) if umin != None: vmin = umin else: vmin = v.min() if umax != None: vmax = umax else: vmax = v.max() # countour levels : if scale == 'log': v[v < vmin] = vmin + 1e-12 v[v > vmax] = vmax - 1e-12 from matplotlib.ticker import LogFormatter levels = np.logspace(np.log10(vmin), np.log10(vmax), numLvls) formatter = LogFormatter(10, labelOnlyBase=False) norm = colors.LogNorm() elif scale == 'lin': v[v < vmin] = vmin + 1e-12 v[v > vmax] = vmax - 1e-12 from matplotlib.ticker import ScalarFormatter levels = np.linspace(vmin, vmax, numLvls) formatter = ScalarFormatter() norm = None elif scale == 'bool': from matplotlib.ticker import ScalarFormatter levels = [0, 1, 2] formatter = ScalarFormatter() norm = None fig = plt.figure(figsize=(5, 5)) ax = fig.add_subplot(111) c = ax.tricontourf(x, y, t, v, levels=levels, norm=norm, cmap=plt.get_cmap(cmap)) plt.axis('equal') if tp == True: p = ax.triplot(x, y, t, '-', lw=0.2, alpha=tpAlpha) ax.set_xlim([x.min(), x.max()]) ax.set_ylim([y.min(), y.max()]) if label_axes: ax.set_xlabel(r'$x$') ax.set_ylabel(r'$y$') if hide_ax_tick_labels: ax.set_xticklabels([]) ax.set_yticklabels([]) if hide_axis: plt.axis('off') # include colorbar : if scale != 'bool' and use_colorbar: divider = make_axes_locatable(plt.gca()) cax = divider.append_axes(colorbar_loc, "5%", pad="3%") cbar = plt.colorbar(c, cax=cax, format=formatter, ticks=levels) tit = plt.title(title) if use_colorbar: plt.tight_layout(rect=[.03, .03, 0.97, 0.97]) else: plt.tight_layout() plt.savefig(os.path.join(direc, name + '.png'), dpi=300) if show: plt.show() plt.close(fig)
import matplotlib.pyplot as plt # Creating dataset z = pvr[:, 0] x = pvr[:, 1] y = psr # Creating figure fig = plt.figure(figsize=(25, 11)) ax = plt.axes(projection="3d") # Add x, y gridlines ax.grid(b=True, color='black', linestyle='--', linewidth=0.3, alpha=0.8) # Creating color map my_cmap = plt.get_cmap('coolwarm') # Creating plot sctt = ax.scatter3D(x, y, z, alpha=1, c=(x + y + z), cmap=my_cmap, marker='*') plt.title(' | '.join(symbols)) ax.set_xlabel('expected volatility', fontweight='bold') ax.set_ylabel('expected return', fontweight='bold') ax.set_zlabel('Sharpe ratio', fontweight='bold') fig.colorbar(sctt, ax=ax, shrink=0.5, aspect=5) # show plot plt.show() bnds = len(symbols) * [ (0, 1),
signals = extract_activity_signals(activity, resample='existing') power = signals['power'] balance = signals['left_right_balance'] time = signals['time'] PAvgBalance = sum(power * balance) / sum(power) # get session info records = activity.get_records_by_type('session') for record in records: valid_field_names = record.get_valid_field_names() # plotting CrossPlotFig = plt.figure() sc = plt.scatter(power, balance, s=5, c=time, cmap=plt.get_cmap('brg'), edgecolors='face') plt.colorbar(orientation='horizontal') plt.title('Balance Vs Power over Time (sec)\n' \ + 'power-weighted average = %4.1f' % (PAvgBalance) ) plt.xlabel('Power (w)') plt.ylabel('Right Balance (%)') plt.grid(b=True, which='major', axis='both') ax = plt.gca() grids = arange(10, 100, 10) # force a gride at 50 ax.set_yticks(grids, minor=False) ax.grid(True) plt.show()