def plot_sentiment_by_country(data_mails, opt, nb_country=20): ''' This function plots sentiment of countries (countries are filtered by sentiment). This function uses 4 colors to evaluate the occurrences of given countries. Abscissa: countries / Ordinate: sentiment / Color: occurrences Parameters - opt : allow to select the option of the graph - 'only_good' = keep only good feeling - 'only_bad' = keep only bad feeling - <empty> = concatenate good and bad feeling in same plot - data_mails : DataFrame containing the data (emails) - nb_country : selection of the most representative countries (by default, 20) ''' # Selection of data to be used for the plot if opt == 'only_good': data_plot = data_mails.nlargest(nb_country, 'Sentiment') title = 'Hilary\'s opinion for the ' + str( nb_country) + ' most-preferred countries' elif opt == 'only_bad': data_plot = data_mails.nsmallest(nb_country, 'Sentiment') title = 'Hilary\'s opinion for the ' + str( nb_country) + ' less-preferred countries' else: most_liked = data_mails.nlargest(nb_country, 'Sentiment') worst_liked = data_mails.nsmallest(nb_country, 'Sentiment') data_plot = pd.concat([most_liked, worst_liked]) title = 'Hilary\'s opinion for the ' + str( nb_country) + ' most- and less-preferred countries' data_plot.sort_values(by='Sentiment', ascending=False, inplace=True) # Definition of the gradation of color y = np.array(np.log(data_plot['Occurrences'])) colors = cm.BrBG(y / float(max(y))) plot = plt.scatter(y, y, c=y, cmap='BrBG') plt.clf() clb = plt.colorbar(plot) clb.ax.set_title('Occurences (log)') # Creation of the plot sentiment_data_plot = sns.barplot(x=data_plot.index, y='Sentiment', data=data_plot, palette=colors) # Display of a line to separate the graph (static line, for delimitation of 20 most- and less-preferred countries) define_plot_title_and_labels(sentiment_data_plot, title=title) if opt == None and nb_country == 20: sentiment_data_plot.axvline(nb_country - 0.5) sns.plt.show()
def getECColour(_log, EC): _log.info("getECColour(_log, EC) EC = " + str(EC)) #normalize item number values to colormap norm = matplotlib.colors.Normalize(vmin=0, vmax=2000) #colormap possible values = viridis, jet, spectral,gist_rainbow, BrBG rgba_color = cm.BrBG(norm(int(EC)), bytes=True) _log.info("rgba_color =" + str(rgba_color)) c = Color(rgb=(rgba_color[0] / 255, rgba_color[1] / 255, rgba_color[2] / 255)) _log.info("getECColour =" + str(c)) return c
def show_graph(g, pos, partition_dic, colorful, str_type): n = g.number_of_nodes() plt.figure(figsize=(30, 30)) # Read color for points color_max = len(partition_dic.keys()) # Different color for different clusters/partition color_index = 0 color_general_index = 0 # Blue edges nx.draw_networkx_edges(g, pos, edge_color='b', alpha=0.3) for represent in partition_dic.keys(): # if it's a little cluster/partition -> more transparency if len(partition_dic[represent]) > 10: alpha = 0.8 else: alpha = 0.1 # If there are no more than 5 partitions with size bigger than 1 then print with colorful layout if colorful and len(partition_dic[represent]) > 1: color = color_general[color_general_index] color_general_index += 1 alpha = 0.8 else: color = cm.BrBG(color_index / color_max) # If type = dbscan -> the cluster with 1 point will not be drawn if str_type != "dbscan" or len(partition_dic[represent]) > 2: for point in partition_dic[represent]: try: nx.draw_networkx_nodes(g, pos, nodelist=[point], node_color=[color], node_size=100, alpha=alpha) except nx.exception.NetworkXError: continue color_index += 1 # Figure settings plt.axis('off') plt.show(block=False) plt.savefig(sys.argv[1].replace("edges.txt", str_type + ".png")) return 0
def draw(nb_points, xs, ys, froms, tos, partition_dic, fig): # Check if point is not noise (cluster size < 2) points = [] for represent in partition_dic.keys(): for point in partition_dic[represent]: points.append(point) if len(points) == 0: print("No cluster detected!") return 1 # Print edges for edge in range(len(froms)): from_loc = froms[edge] to_loc = tos[edge] if from_loc in points and to_loc in points: fig.arrow(xs[from_loc], ys[from_loc], xs[to_loc] - xs[from_loc], ys[to_loc] - ys[from_loc], color='m', alpha=0.1) # Print points color_max = len(partition_dic.keys()) color_index = 0 for represent in partition_dic.keys(): r, g, b, a = cm.BrBG(color_index / color_max) for point in partition_dic[represent]: fig.scatter(xs[point], ys[point], c=np.array([[r, g, b, a]]), zorder=2) color_index += 1 # Set limits : fig.set_xlim(np.min(xs) - 0.1, np.max(xs) + 0.1) fig.set_ylim(np.min(ys) - 0.1, np.max(ys) + 0.1)
def draw_perc_agw(ax, geom, vals, debug=False): for g, val in zip(geom, vals): if np.isfinite(val): if debug: x = g.centroid.x y = g.centroid.y ax.text(x, y, str(int(val)), transform=ccrs.PlateCarree()) quant = quantize_perc_agw(val) facecolor = cm.BrBG(quant / 10) else: facecolor = 'grey' ax.add_geometries([g], ccrs.PlateCarree(), facecolor=facecolor, edgecolor=facecolor)
set_plot_parameters() fig1 = plt.figure("pressure") plt.clf() #plt.subplots_adjust(right=0.75) #plt.figtext(0.77,0.70, param_text,ha='left',va='top',size='x-small') fig2 = plt.figure("density") plt.clf() # Loop thru particles count = 0 for particle_id in particle_ids: count = count + 1 particle_data = partextract(extract_exe, work_dir, uda_name, plot_dir, particle_id) plt_color = cm.BrBG(float(count) / float(len(particle_ids))) plot_pressure(particle_data, particle_id, plt_color) plot_density(particle_data, particle_id, plt_color) plt.figure("pressure") plt.grid(True) plt.legend(loc='best', prop={'size': 10}) savePDF(fig1, 'pressure_vs_time', size='1280x960') plt.figure("density") plt.grid(True) #plt.legend(loc='best', prop={'size':10}) savePDF(fig2, 'density_vs_time', size='1280x960') plt.show()
import pandas as pd import geopandas as gpd import folium import matplotlib.cm as cm cuomo = 'ANDREW M. CUOMO' nixon = 'CYNTHIA E. NIXON' frac = 'cuomo_over_cuomo_plus_nixon' def rgb_to_hex(rgb): f = lambda x: int(x * 255) return '#%02X%02X%02X' % (f(rgb[0]), f(rgb[1]), f(rgb[2])) colormap = lambda x: rgb_to_hex(cm.BrBG(x)) df = pd.read_csv('20180913__ny__primary__nyc__precinct.csv') gdf = gpd.read_file('shapefile/nyed.shp') df['ElectDist'] = df['assembly district'].astype( str) + df['election district'].apply(lambda x: str(x).zfill(3)) gov = df.pivot_table(index='ElectDist', columns='candidate', values='votes', aggfunc=sum)[[cuomo, nixon]].astype(int) gov[frac] = gov[cuomo] / (gov[cuomo] + gov[nixon]) gdf['ElectDist'] = gdf['ElectDist'].astype(str)
prob_ChR2=prob_ChR2, frequency_A_ChR2=np.ascontiguousarray(frequency_A_ChR2), ref_spectra_ChR2=np.ascontiguousarray(absorption_ChR2), Raman_levels_ChR2=Raman_levels_ChR2, levels_ChR2=levels_ChR2, # GEVI molecule energies_GEVI=energies_GEVI, gamma_dep_GEVI=gamma_dep_GEVI, prob_GEVI=prob_GEVI, frequency_A_GEVI=np.ascontiguousarray(frequency_A_GEVI), ref_spectra_GEVI=np.ascontiguousarray(absorption_GEVI), Raman_levels_GEVI=Raman_levels_GEVI, levels_GEVI=levels_GEVI) colors = [cm.BrBG(x) for x in np.linspace(0., 1., M, endpoint=True)] # ------------------------ SETTING UP PLOT GRIDS --------------------- # # gs_top = plt.GridSpec(5, 2, top=0.95, hspace=0.2, wspace=0.05) # gs_base = plt.GridSpec(5, 2, hspace=0.025, wspace=0.01) # fig = plt.figure(figsize=(14, 11)) # axbig1 = fig.add_subplot(gs_top[:2, 0]) # axbig2 = fig.add_subplot(gs_top[:2, 1]) # # axes = [[fig.add_subplot(gs_base[i, j]) for j in range(2)] for i in range(2, 5)] # # axbig2.set_yticklabels([]) # for i in range(2): # axes[i][1].set_yticklabels([]) # for j in range(2):
drawbounds=True) # collect the state names from the shapefile attributes so we can look up the shape obect for a state by it's name names = [] colors = {} i = 0 for shape_dict in m.states_info: names.append(shape_dict['HASC_1']) if shape_dict['HASC_1'] in corSTs.keys(): colors[ shape_dict['HASC_1']] = corSTs[shape_dict['HASC_1']] / 2 + 0.5 else: colors[shape_dict['HASC_1']] = 0.5 ax = plt.gca() # get current axes instance for nshape, seg in enumerate(m.states): poly = Polygon(seg, facecolor=cm.BrBG(colors[names[nshape]]), edgecolor='k') ax.add_patch(poly) ARshp = m.readshapefile( '/Volumes/Data_Archive/Data/adminBoundaries/GADM/ARG_adm_shp/ARG_adm1', name='states', drawbounds=True) # collect the state names from the shapefile attributes so we can look up the shape obect for a state by it's name names = [] colors = {} i = 0 for shape_dict in m.states_info: names.append(shape_dict['HASC_1']) if shape_dict['HASC_1'] in corSTs.keys(): colors[ shape_dict['HASC_1']] = corSTs[shape_dict['HASC_1']] / 2 + 0.5