Python matplotlib.pyplot.hexbin() Examples

The following are code examples for showing how to use matplotlib.pyplot.hexbin(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: radiometric_normalization   Author: planetlabs   File: display.py    Apache License 2.0 6 votes vote down vote up
def plot_pixels(file_name, candidate_data_single_band,
                reference_data_single_band, limits=None, fit_line=None):

    logging.info('Display: Creating pixel plot - {}'.format(file_name))
    fig = plt.figure()
    plt.hexbin(
        candidate_data_single_band, reference_data_single_band, mincnt=1)
    if not limits:
        min_value = 0
        _, ymax = plt.gca().get_ylim()
        _, xmax = plt.gca().get_xlim()
        max_value = max([ymax, xmax])
        limits = [min_value, max_value]
    plt.plot(limits, limits, 'k-')
    if fit_line:
        start = limits[0] * fit_line.gain + fit_line.offset
        end = limits[1] * fit_line.gain + fit_line.offset
        plt.plot(limits, [start, end], 'g-')
    plt.xlim(limits)
    plt.ylim(limits)
    plt.xlabel('Candidate DNs')
    plt.ylabel('Reference DNs')
    fig.savefig(file_name, bbox_inches='tight')
    plt.close(fig) 
Example 2
Project: StackedDAE   Author: glrs   File: visualize.py    Apache License 2.0 6 votes vote down vote up
def make_2d_hist(data, name):
    f = plt.figure()
    X,Y = np.meshgrid(range(data.shape[0]), range(data.shape[1]))
    im = plt.pcolormesh(X,Y,data.transpose(), cmap='seismic')
    plt.colorbar(im, orientation='vertical')
#     plt.hexbin(data,data)
#     plt.show()
    f.savefig(pjoin(FLAGS.output_dir, name + '.png'))
    plt.close()
    
# def make_2d_hexbin(data, name):
#     f = plt.figure()
#     X,Y = np.meshgrid(range(data.shape[0]), range(data.shape[1]))
#     plt.hexbin(X, data)
# #     plt.show()
#     f.savefig(pjoin(FLAGS.output_dir, name + '.png')) 
Example 3
Project: rapala   Author: legacysurvey   File: checkfields.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def plot_cfhtls_snr_ratio(snr1='snrRMS',snr2='snrETCrev'):
	hdus = fitsio.FITS('cfhtlswide_snr.fits')
	ccds = [hdu.read() for hdu in hdus[1:]]
	plt.figure()
	for pnum,ccd in enumerate(ccds,start=1):
		ax = plt.subplot(2,2,pnum)
		plt.hexbin(ccd['refMag'],ccd[snr1]/ccd[snr2],
		           extent=(20,23.5,0.5,1.5),cmap=plt.cm.Blues)
		plt.axhline(1,c='r')
		ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
		ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.25))
		ax.yaxis.set_major_locator(ticker.MultipleLocator(0.2))
		ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.05))
		ax.set_title('CCD%d'%pnum)
	plt.figtext(0.01,0.5,'SNR/SNR(ETC)',va='center',rotation='vertical')
	plt.figtext(0.5,0.01,'g mag (CFHTLS)',ha='center')




##############################################################################
#                                                                            #
#                         Pan-STARRS Medium Deeps                            #
#                                                                            #
############################################################################## 
Example 4
Project: Kobe-Analysis   Author: codeabhious   File: kobeanalysis.py    Apache License 2.0 5 votes vote down vote up
def find_shootingPcts(kobe_df,kobeyear, gridNum,isClutch):
    np.seterr(divide='ignore', invalid='ignore')
    kobeyear_df = kobe_df.loc[kobe_df['season'] == kobeyear]
    if isClutch:
        kobeyear_df = kobeyear_df.loc[kobeyear_df['period'] >=4]
        kobeyear_df = kobeyear_df.loc[kobeyear_df['minutes_remaining']  <=5]
         #get kobe's year
    x = kobe_df.loc_x[kobe_df['loc_y']<425.1] #i want to make sure to only include shots I can draw
    y = kobe_df.loc_y[kobe_df['loc_y']<425.1]
    x_year = kobeyear_df.loc_x[kobeyear_df['loc_y']<425.1]
    y_year = kobeyear_df.loc_y[kobeyear_df['loc_y']<425.1]

    x_made = kobe_df.loc_x[(kobe_df['shot_made_flag']==1) & (kobe_df['loc_y']<425.1)]
    x_yearmade = kobeyear_df.loc_x[(kobeyear_df['shot_made_flag']==1) & (kobeyear_df['loc_y']<425.1)]
    y_made = kobe_df.loc_y[(kobe_df['shot_made_flag']==1) & (kobe_df['loc_y']<425.1)]
    y_yearmade = kobeyear_df.loc_y[(kobeyear_df['shot_made_flag']==1) & (kobeyear_df['loc_y']<425.1)]

    #compute number of shots made and taken from each hexbin location
    hb_shot = plt.hexbin(x, y, gridsize=gridNum, extent=(-250,250,425,-50));
    plt.close() #don't want to show this figure!
    hb_shotyear = plt.hexbin(x_year,y_year, gridsize = gridNum, extent = (-250,250,425,-50));
    plt.close()
    hb_made = plt.hexbin(x_made, y_made, gridsize=gridNum, extent=(-250,250,425,-50),cmap=plt.cm.Reds);
    plt.close()
    hb_madeyear = plt.hexbin(x_yearmade,y_yearmade, gridsize=gridNum, extent=(-250,250,425,-50),cmap=plt.cm.Reds);
    plt.close()
    #compute shooting percentage
    ShootingPctLocs = (hb_madeyear.get_array()/hb_shotyear.get_array())/(hb_made.get_array() / hb_shot.get_array())
    ShootingPctLocs[np.isnan(ShootingPctLocs)] = 0 #makes 0/0s=0
    shootingFreqLocs = hb_shotyear.get_array() / hb_shot.get_array()
    shootingFreqLocs[np.isnan(shootingFreqLocs)] = 0
    return (ShootingPctLocs, hb_shotyear,shootingFreqLocs)
#find_shootingPcts(x,2001,30) 
Example 5
Project: Lie_to_me   Author: Notabela   File: thinkplot.py    MIT License 5 votes vote down vote up
def HexBin(xs, ys, **options):
    """Makes a scatter plot.

    xs: x values
    ys: y values
    options: options passed to plt.scatter
    """
    options = _Underride(options, cmap=matplotlib.cm.Blues)
    plt.hexbin(xs, ys, **options) 
Example 6
Project: nested-sampling   Author: JohannesBuchner   File: ultranest_postprocess.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def marginal_plot(x, w, i, j = None, grid_points = 40, **kwargs):
	if j is None:
		hist, bins = numpy.histogram(x[:,i], weights=w, bins=100)
		hist /= hist.max()
		plt.bar((bins[:-1] + bins[1:])/2., hist, width=(bins[1:] - bins[:-1]),
			color='grey', alpha=0.3, linewidth=0)
		plt.hist(x[:,i], weights=w, histtype='step', color='blue', 
			normed=True, bins=1000, cumulative=True)
		plt.ylim(0, 1)
	else:
		plt.hexbin(x=x[:,i], y=x[:,j], gridsize=grid_points, 
			C = w, reduce_C_function=numpy.nansum,
                        **kwargs) 
Example 7
Project: nested-sampling   Author: JohannesBuchner   File: postprocess.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def marginal_plot(x, w, i, j = None, grid_points = 40, **kwargs):
	if j is None:
		hist, bins = numpy.histogram(x[:,i], weights=w, bins=100)
		hist /= hist.max()
		plt.bar((bins[:-1] + bins[1:])/2., hist, width=(bins[1:] - bins[:-1]),
			color='grey', alpha=0.3, linewidth=0)
		plt.hist(x[:,i], weights=w, histtype='step', color='blue', 
			normed=True, bins=1000, cumulative=True)
		plt.ylim(0, 1)
	else:
		plt.hexbin(x=x[:,i], y=x[:,j], gridsize=grid_points, 
			C = w, reduce_C_function=numpy.nansum,
                        **kwargs) 
Example 8
Project: smp_base   Author: x75   File: plot.py    MIT License 5 votes vote down vote up
def histogramnd(ax, data, **kwargs):
        """n-dimensional histogram seaborn based
        """
        scatter_data_raw  = data
        scatter_data_cols = ["x_%d" % (i,) for i in range(data.shape[1])]

        # prepare dataframe
        df = pd.DataFrame(scatter_data_raw, columns=scatter_data_cols)
        
        g = sns.PairGrid(df)
        # g.map_diag(plt.hist)
        g.map_diag(sns.kdeplot)
        g.map_offdiag(plt.hexbin, cmap="gray", gridsize=30, bins="log");

        # logger.log(loglevel_debug, "dir(g)", dir(g))
        # print g.diag_axes
        # print g.axes
    
        # for i in range(data.shape[1]):
        #     for j in range(data.shape[1]): # 1, 2; 0, 2; 0, 1
        #         if i == j:
        #             continue
        #         # column gives x axis, row gives y axis, thus need to reverse the selection for plotting goal
        #         # g.axes[i,j].plot(df["%s%d" % (self.cols_goal_base, j)], df["%s%d" % (self.cols_goal_base, i)], "ro", alpha=0.5)
        #         g.axes[i,j].plot(df["x_%d" % (j,)], df["x_%d" % (i,)], "ro", alpha=0.5)
                
        plt.show()

    
        # run sns scattermatrix on dataframe
        # plot_scattermatrix(df, ax = None) 
Example 9
Project: Data-digging   Author: zooniverse   File: talk_contributions.py    MIT License 5 votes vote down vote up
def plot_results(talkers,classifiers,savefig=False):

    plt.subplot(111)

    x,y,s = [],[],[]

    count_talkers = Counter(talkers)
    count_classifiers = Counter(classifiers)

    for k in count_talkers:
        if count_classifiers.has_key(k):
            x.append(count_talkers[k])
            y.append(count_classifiers[k])

    xmin = np.min(x)
    xmax = np.max(x)
    ymin = np.min(y)
    ymax = np.max(y)

    plt.hexbin(x,y,gridsize=(20,20),bins='log',cmap=plt.cm.viridis)
    plt.axis([xmin,xmax,ymin,ymax])
    cb = plt.colorbar()
    cb.set_label(r'$\log_{10} N$')

    plt.xlabel(r'$N_{talk comments}$',fontsize=25)
    plt.ylabel(r'$N_{classifications}$',fontsize=25)

    plt.tight_layout()
    if savefig:
        plt.savefig('talk_contributions_{0}.png'.format(project_name))
    else:
        plt.show()

    return None 
Example 10
Project: abtools   Author: briney   File: _finder.py    MIT License 5 votes vote down vote up
def make_figure(standard_id, scores, collection, args):
    print_fig_info()
    sns.set_style('white')
    fig_file = os.path.join(args.output_dir, '{0}_{1}_{2}.pdf'.format(args.db, collection, standard_id))
    x = list(scores['germ_divergence'].values)
    y = list(scores['identity'].values)
    xy_vals = zip(x, y)
    trunc_xy_vals = [v for v in xy_vals if v[0] <= args.x_max and v[1] >= args.y_min]
    x = [v[0] for v in trunc_xy_vals]
    y = [v[1] for v in trunc_xy_vals]
    # To make sure the gridsize is correct (since it's based on the actual values)
    # I need to add a single value near the max and min of each axis.
    # They're added just outside the visible plot, so there's no effect on the plot.
    x.extend([args.x_min - 1, args.x_max + 1])
    y.extend([args.y_min - 1, args.y_max + 1])
    # plot params
    cmap = color.get_cmap(args.colormap)
    plt.subplots_adjust(hspace=0.95)
    plt.subplot(111)
    plt.hexbin(x, y, bins='log', cmap=cmap, mincnt=3, gridsize=set_gridsize(args))
    plt.title(standard_id, fontsize=18)
    # set and label axes
    plt.axis([args.x_min, args.x_max, args.y_min, args.y_max])
    plt.xlabel('Germline divergence')
    plt.ylabel('{0} identity'.format(standard_id))
    # make and label the colorbar
    cb = plt.colorbar()
    cb.set_label('Sequence count (log10)', labelpad=10)
    # save figure and close
    plt.savefig(fig_file)
    plt.close() 
Example 11
Project: samoo   Author: proteekroy   File: cdtlz_problems_main.py    MIT License 4 votes vote down vote up
def plot_test_problem(axarr, F, problem, type=1):

    F1 = F[:, 0].flatten()
    F2 = F[:, 1].flatten()

    c = list([1, 4, 3])
    constr_func = dict()
    for i in c:
        if i == 1:
            constr_func[str(i)] = constraint_c1
        elif i == 2:
            constr_func[str(i)] = constraint_c2
        elif i == 3:
            constr_func[str(i)] = constraint_c3
        elif i == 4:
            constr_func[str(i)] = constraint_c4
    # plt.clf()
    index= np.ones(F.shape[0], dtype=bool)

    for i in range(len(constr_func)):
        G = constr_func[str(c[i])](F, dtlz_type=type)
        cv = np.copy(G) # np.zeros(G.shape)

        light_grey = np.array([220,220,220])/256
        dark_grey = np.array([169, 169, 169])/256
        cv[G <= 0] = 0
        if G.ndim>1:
            cv = np.sum(cv, axis=1)

        temp_index = cv <= 0
        index = index & temp_index
        # axarr[index].plot(x, y)
        # cmaps = OrderedDict()
    plt.plot(F1, F2, 'o', color='#DCDCDC') #'#A9A9A9'
    plt.plot(F1[index], F2[index], 'o', color='b')
        # F_all = np.concatenate((F, np.vstack(cv)),axis=1)
        # heatmap, xedges, yedges = np.histogram2d(F1, F2, weights=cv, )
        # extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
        # plt.hexbin(F1[index], F2[index], C=cv, cmap='Greys')

        # ax.clf()
        # plt.imshow(heatmap.T, extent=extent, origin='lower', cmap='Greys')
    ref_dirs = UniformReferenceDirectionFactory(n_dim=2, n_points=21)._do()
    PF = problem._calc_pareto_front(ref_dirs)
    plt.plot(PF[:, 0], PF[:, 1], 'o', color='r')
    plt.show()

        # df2 = pd.DataFrame(F_all)
        # df.to_csv('a.csv', index=False)
        # df2 = pd.read_csv('a.csv')
        # df3 = df2.pivot()
        # seaborn.heatmap(df3)
        # seaborn.heatmap()
        # plt.show()

# DTLZ1, r = 20
# problems = [('DTLZ1', [2, 2]), ('DTLZ2', [2, 2]), ('DTLZ3', [2, 2]), ('DTLZ4', [2, 2])]
# problems = [('DTLZ1', [2, 2])] 
Example 12
Project: cs229   Author: kmckiern   File: plt_dm.py    MIT License 4 votes vote down vote up
def main():
    opref = args.opref

    data_file = args.df
    data_name = data_file.split('/')[-1].split('.')[0]
    df = pd.read_pickle(data_file)
    df_col = df.columns

    cmin = 0 # float(df.min().min())
    cmax = float(df.max().max())

    grid_kws = {"height_ratios": (.95, .05), "hspace": .25}
    fig, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws)
    ax = sns.heatmap(df.T, vmin=cmin, vmax=cmax, cmap=cm, ax=ax, 
            xticklabels=False, cbar_ax=cbar_ax,
            cbar_kws={'orientation': 'horizontal'})
    ax.set_title('Normalized Campaign Contributions by Sector')
    ax.set_xlabel('Candidate')
    plt.yticks(rotation=0)
    fig.savefig(opref + data_name + '_feature_hm.png', bbox_inches='tight')

    nc = args.pca
    if nc > 0:
        from sklearn.decomposition import PCA
        pca = PCA(n_components = nc)
        pca.fit(df)
        PCs = pca.components_
        cols = ['PC ' + str(i) for i in range(PCs.shape[0])]
        pc_df = pd.DataFrame(PCs.T, columns=cols)
        pc_df.index = df_col

        grid_kws = {"height_ratios": (.95, .05), "hspace": .25}
        fig, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws)
        ax = sns.heatmap(pc_df, cmap=cm, ax=ax, 
                xticklabels=False, cbar_ax=cbar_ax,
                cbar_kws={'orientation': 'horizontal'})
        ax.set_title('Feature Matrix Principal Components')
        plt.yticks(rotation=0)
        ax.set_xlabel('PC')
        fig.savefig(opref + data_name + '_pc_hm.png', bbox_inches='tight')

        plt.clf()
        g = sns.PairGrid(pc_df)
        g.map_lower(plt.hexbin, gridsize=30, mincnt=1, cmap=cm,
                edgecolor='none')
        g.map_diag(sns.kdeplot, lw=1, legend=False)
        g.savefig(opref + data_name + '_pc_pg.png', bbox_inches='tight') 
Example 13
Project: rapala   Author: legacysurvey   File: diagplots.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plot_relphot(colorfix=True):
	from astrotools.idmstuff import binmean
	magbins = np.arange(17.,21.1,1.0)
	p = fits.getdata('sdssrm_relphot.fits')
	mi = np.digitize(p['refMag'],magbins) - 1
	logsky = np.log10(p['skyADU'])
	skybins = np.arange(2.5,4.51,0.20)
	dmbins = np.arange(-0.15,0.151,0.01)
	xb = skybins[:-1]+np.diff(skybins)/2
	yb = dmbins[:-1]+np.diff(dmbins)/2
	good = np.where((p['dmag']>-0.2)&(p['dmag']<0.2))[0]
	if colorfix:
		dmag = p['dmag'] - np.polyval(bok2cfht,p['ref_gmr'])
		outfn = 'sdssrm_relphot'
	else:
		dmag = p['dmag']
		outfn = 'sdssrm_relphot_nocolorfix'
	pdf = PdfPages(outfn+'.pdf')
	for amp in range(16):
		if amp%8==0:
			fig = plt.figure(figsize=(8.0,10))
			plt.subplots_adjust(0.08,0.08,0.92,0.92,0.3,0.35)
			pnum = 1
		#
		amp_ii = good[np.where(p['ampNum'][good]==amp)[0]]
		for j in range(len(magbins)-1):
			mag_ii = np.where(mi[amp_ii]==j)[0]
			n,_,_ = np.histogram2d(logsky[amp_ii[mag_ii]],
			                       dmag[amp_ii[mag_ii]],
			                       [skybins,dmbins])
			b,mdm,sdm = binmean(logsky[amp_ii[mag_ii]],
			                    dmag[amp_ii[mag_ii]],
			                    skybins,std=True,clip=True)
			#plt.figure()
			ax = plt.subplot(8,4,pnum)
#			plt.hexbin(logsky[amp_ii[mag_ii]],dmag[amp_ii[mag_ii]],
#			           gridsize=40,cmap=plt.cm.Blues)
			plt.contour(xb,yb,n.transpose(),colors='gray')
			plt.errorbar(b,mdm,sdm,c='b')
#			plt.imshow(n.transpose(),interpolation='nearest')
			plt.axhline(0,c='r')
			plt.xlim(2.2,4.6)
			plt.ylim(-0.15,0.15)
			for tick in ax.xaxis.get_major_ticks()+ax.yaxis.get_major_ticks():
				tick.label1.set_fontsize(7)
			if j==0:
				ax.text(0.03,0.9,'#%d'%rm_ampmap[amp],size=9,va='top',
				        transform=ax.transAxes)
			if amp%8==0:
				ax.set_title('$%.1f < g < %.1f$' % 
				             (magbins[j],magbins[j+1]),size=11)
			pnum += 1
#		return
		if amp%8==7:
			pdf.savefig(fig)
			plt.close()
	pdf.close()