def scat_plot():
f = plt.figure()
# filename = 'MLP5_dap_multi_' + str(plate) + '_quicklook.pdf'
mpl5_dir = os.environ['MANGADIR_MPL5']
drp = fits.open(mpl5_dir + 'drpall-v2_0_1.fits')
drpdata = drp[1].data
absmag = drpdata.field('nsa_elpetro_absmag')
plt.xlim(-16,-24)
plt.ylim(1,7)
plt.scatter(absmag[:,5], absmag[:,1]-absmag[:,5], marker='.',color=['blue'], s=0.5)
plt.xlabel('i-band absolute magnitude', fontsize=16)
plt.ylabel('NUV - i', fontsize=16)
plt.tick_params(axis='both', labelsize=14)
ifu_list = drpdata.field('plateifu')
for i in good_galaxies:
ithname = str(i[0]) + str(i[1])
for e in range(0, len(ifu_list)):
ethname = ifu_list[e]
ethname = ethname.replace("-","")
if ithname == ethname:
plt.scatter(absmag[e, 5], absmag[e, 1] - absmag[e, 5], marker='*',color=['red'])
f.savefig("scatter.pdf", bbox_inches='tight')
# pp = PdfPages('scatter.pdf')
# pp.savefig(plot_1)
plt.close()
os.system("open %s &" % 'scatter.pdf')
python类PdfPages()的实例源码
def draw_rader_chart_hotel(lat, lng, df):
"""
This function call the method in class 'ComplexRadar' to draw the rader chart for each recommend hotel,
and create a pdf with hotels name and rader chart.
Parameters:
lat: float
lng: float
df: Dataframe
Return:
create a pdf file
"""
variables_hotel = ("Avgscore", "Clean", "Comfort", "Facilities", "Free_Wifi", "Staff", "Value_for_money",
"Location", "Price")
ranges_hotel = [(5, 10), (5, 10), (5, 10), (5, 10), (5, 10),
(5, 10), (5, 10), (5, 10),
(0.00001, 5)]
data = list(zip(df.Avgscore, df.Cleanliness, df.Comfort, df.Facilities, df['Free Wifi'], df.Staff, df['Value for money'], df.Location, df.Price))
information = list(zip(df.Name))
path = os.path.abspath("Results")
pp = PdfPages(filename = path + '/Recommendation_hotels.pdf')
for i in range(len(data)):
fig = plt.figure(i, figsize=(4, 6))
rader = ComplexRadar(fig, variables_hotel, ranges_hotel)
rader.plot(data[i])
rader.fill(data[i], alpha=0.2)
text = 'Hotel Name: ' + str(information[i][0])
fig.text(0, 0.9, text, fontsize=15, fontweight='bold', color = 'blue')
pp.savefig(bbox_inches = 'tight')
plt.clf()
pp.close()
webbrowser.open_new('file://' + path + '/Recommendation_hotels.pdf')
def draw_rader_chart_restaurant(lat, lng, df):
"""
This function call the method in class 'ComplexRadar' to draw the rader chart for each recommend restaurant,
and create a pdf with restaurants name and rader chart.
Parameters:
lat: float
lng: float
df: Dataframe
Return:
create a pdf file
"""
variables_restaurant = ('number_of_price', 'Reviews', 'score_of_review', 'Distance')
ranges_restaurant = [(0.00001, 5), (0.00001, 5), (0.00001, 5), (0.00001, 10)]
data = list(zip(df['number_of_price'], df['Reviews'], df['Avgscore'], df['Distance']))
information = list(zip(df['Name']))
path = os.path.abspath("Results")
pp = PdfPages(filename = path + '/Recommendation_restaurants.pdf')
for i in range(len(data)):
fig = plt.figure(i, figsize=(4, 6))
rader = ComplexRadar(fig, variables_restaurant, ranges_restaurant)
rader.plot(data[i])
rader.fill(data[i], alpha=0.2)
text = 'Restaurant Name: ' + str(information[i][0])
fig.text(0, 0.9, text, fontsize=15, fontweight='bold', color = 'blue')
pp.savefig(bbox_inches = 'tight')
plt.clf()
pp.close()
webbrowser.open_new('file://' + path + '/Recommendation_restaurants.pdf')
def make_plots(self):
"""
Make plots for :py:class:`~seqlib.seqlib.OverlapSeqLib` objects.
Creates plots of the location of merged read mismatches.
"""
if self.plots_requested:
SeqLib.make_plots(self)
pdf = PdfPages(os.path.join(self.plot_dir, "overlap_mismatches.pdf"))
overlap_merge_plot(self, pdf)
pdf.close()
def make_plots(self):
"""
Make plots for :py:class:`~seqlib.seqlib.BcvSeqLib` objects.
Creates plot of the number of barcodes mapping to each variant.
"""
if self.plots_requested:
SeqLib.make_plots(self)
# open the PDF file
pdf = PdfPages(os.path.join(self.plot_dir, "barcodes_per_variant.pdf"))
barcodemap_plot(self, pdf)
pdf.close()
def volcano_plot(self, label, pdf, colors="YlGnBu_r", log_bins=True):
"""
Create a volcano plot (p-value vs. functional score).
*label* is the data label (barcode, variant, etc.)
*pdf* is an open PdfPages instance.
The p-values used are the regression p-values (p-value of non-zero slope). Due to the large number of points, we use a hexbin plot showing the density instead of a scatter plot.
"""
logging.info("Creating volcano plot ({})".format(label), extra={'oname' : self.name})
# get the data
data = self.store.select("/main/{}/scores".format(label), "columns=['score', 'pvalue_raw']")
volcano_plot(data, pdf, title="{} ({})".format(self.name, label.title()), colors=colors, log_bins=log_bins)
def make_plots(self):
"""
Make plots that are shared by all :py:class:`~seqlib.seqlib.SeqLib`
objects.
Creates counts histograms for all labels.
"""
if self.plots_requested:
logging.info("Creating plots", extra={'oname': self.name})
pdf = PdfPages(os.path.join(self.plot_dir, "counts.pdf"))
for label in self.labels:
counts_plot(self, label, pdf, log=True)
counts_plot(self, label, pdf, log=False)
pdf.close()
def make_plots(self):
"""
Make plots for :py:class:`~seqlib.seqlib.BcidSeqLib` objects.
Creates plot of the number of barcodes mapping to each identifier.
"""
if self.plots_requested:
SeqLib.make_plots(self)
# open the PDF file
pdf = PdfPages(os.path.join(self.plot_dir, "barcodes_per_identifier.pdf"))
barcodemap_plot(self, pdf)
pdf.close()
def save_plot(is_save, save_path):
if is_save:
pdf = PdfPages(save_path)
pdf.savefig(bbox_inches='tight')
pdf.close()
def setUpModule():
global _plot_filename
global _pdf_out
try:
import matplotlib
matplotlib.use('Agg')
from matplotlib.backends.backend_pdf import PdfPages
_pdf_out = PdfPages(_plot_filename)
except:
_pdf_out = None
def distancePlot(distance_to_start_count,distance_to_stop_count,pre_psite_dict,length_counter,outname):
length_set = set(distance_to_start_count.keys() + distance_to_stop_count.keys())
total_reads = sum(length_counter.values())
with PdfPages(outname + ".pdf") as pdf:
x = np.arange(-50,51,dtype=int)
colors = np.tile(["b","g","r"], 34)
for l in sorted(length_set):
#plt.figure(figsize=(5,3))
if l not in pre_psite_dict:
xticks = [-40,-20,0,20,40]
else:
xticks = sorted([-40,-20,0,20,40] + pre_psite_dict[l] -50)
perct = '{:.2%}'.format(length_counter[l] / total_reads)
fig,(ax1,ax2) = plt.subplots(nrows=2,ncols=1)
y1 = distance_to_start_count[l]
y2 = distance_to_stop_count[l]
ax1.vlines(x,ymin=np.zeros(101),ymax=y1,colors=colors[:-1])
ax1.tick_params(axis='x',which="both",top="off",direction='out')
ax1.set_xticks(xticks)
ax1.set_xlim((-50,50))
ax1.set_xlabel("Distance (nt)")
ax1.set_ylabel("Alignments")
ax1.set_title("({} nt reads,proportion:{})".format(l,perct) + "\n Distance 5'- start codons")
ax2.vlines(x,ymin=np.zeros(101),ymax=y2,colors=colors[:-1])
ax2.tick_params(axis='x',which="both",top="off",direction='out')
ax2.set_xticks(xticks)
ax2.set_xlim((-50,50))
ax2.set_xlabel("Distance (nt)")
ax2.set_ylabel("Alignments")
ax2.set_title("Distance 5'- stop codons")
fig.tight_layout()
pdf.savefig(fig)
plt.close()
return None
def plot_save(path, figs=None, dpi=300):
try:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
pp = PdfPages(path)
if figs is None:
figs = [plt.figure(n) for n in plt.get_fignums()]
for fig in figs:
fig.savefig(pp, format='pdf')
pp.close()
logger.info('Saved pdf figures to:%s' % str(path))
except Exception, e:
logger.error('Cannot save figures to pdf, error:%s' % str(e))
def import_plotting():
global matplotlib
import matplotlib; matplotlib.use('Agg') # for systems without X11
global PdfPages
from matplotlib.backends.backend_pdf import PdfPages
global pylab
import pylab
pylab.rcParams.update({
'backend': 'PDF',
'font.size': 16,
'figure.figsize': (6,4.5),
'figure.dpi': 100.0,
'figure.subplot.left': 0.15,
'figure.subplot.right': 0.95,
'figure.subplot.bottom': 0.15,
'figure.subplot.top': 0.95,
'grid.color': '0.1',
'axes.grid' : True,
'axes.titlesize' : 'small',
'axes.labelsize' : 'small',
'axes.formatter.limits': (-4,4),
'xtick.labelsize' : 'small',
'ytick.labelsize' : 'small',
'lines.linewidth' : 2.0,
'lines.markeredgewidth' : 0.5,
'lines.markersize' : 10,
'legend.fontsize' : 'x-small',
'legend.fancybox' : False,
'legend.shadow' : False,
'legend.borderaxespad' : 0.5,
'legend.numpoints' : 1,
'legend.handletextpad' : 0.5,
'legend.handlelength' : 1.6,
'legend.labelspacing' : .75,
'legend.markerscale' : 1.0,
# turn on the following to embedd fonts; requires latex
#'ps.useafm' : True,
#'pdf.use14corefonts' : True,
#'text.usetex' : True,
})
try: pylab.rcParams.update({'figure.max_num_figures':50})
except: pylab.rcParams.update({'figure.max_open_warning':50})
try: pylab.rcParams.update({'legend.ncol':1.0})
except: pass
def run_plot(args):
import_plotting()
lflist = args.lineformats.strip().split(",")
lfcycle = cycle(lflist)
plot_info = {}
for (path, label) in args.experiments:
dataset_color = lfcycle.next()
dataset_label = label
fin = open(path, 'r')
histograms = json.load(fin)
fin.close()
for name in histograms.keys():
plot_info.setdefault(name, {'datasets':[], 'error':0, 'dataset_colors':[], 'dataset_labels':[], 'bin_labels':[]})
plot_info[name]['dataset_colors'].append(dataset_color)
plot_info[name]['dataset_labels'].append(dataset_label)
dataset = []
bin_labels = []
for (left, right, val) in histograms[name]['bins']:
if right == float('inf'):
right = '{}'.format(r'$\infty$')
elif 'Ratio' not in name:
right = int(right)
if left == float('-inf'):
left = '{}'.format(r'$-\infty$')
elif 'Ratio' not in name:
left = int(left)
bin_labels.append("[{},{})".format(left, right))
dataset.append(val)
plot_info[name]['datasets'].append(dataset)
if 'sigma' in histograms[name]:
sigma = float(histograms[name]['sigma'])
plot_info[name]['error'] = int(round(2 * sqrt(3) * sigma)) % 1000000000000000
if len(plot_info[name]['bin_labels']) == 0:
plot_info[name]['bin_labels'] = bin_labels
page = PdfPages("{0}privcount.results.pdf".format(args.prefix+'.' if args.prefix is not None else ''))
# test data
'''
datasets = [[5, 10, 12, 7, 4], [3, 4, 5, 6, 7]]
dataset_labels = ["tor", "shadow"]
dataset_colors = ["red", "green"]
bar_xlabels = ['[0,128)', '[128,256)', '[256,512)', '[512,1024)', '[1024,\n2048)']
plot_bar_chart(page, datasets, dataset_labels, dataset_colors, bar_xlabels, title="test", xlabel="test_x", ylabel="test_y")
'''
for name in sorted(plot_info.keys()):
dat = plot_info[name]
plot_bar_chart(page, dat['datasets'], dat['dataset_labels'], dat['dataset_colors'], dat['bin_labels'], err=dat['error'], title=name)
page.close()
def __init__(self, file, include_shifted_exponentials: bool = False):
self.doc = PdfPages(file)
self._include_shifted_exponentials = include_shifted_exponentials
def drawXtremIOCharts():
xenvData = np.genfromtxt('xenvPerfStats.csv', dtype=float, delimiter=',', names=True)
xmsData = np.genfromtxt('xmsPerfStats.csv', dtype=float, delimiter=',', names=True)
plot.ioff()
iops = plot.figure(figsize=(20,15))
iops.suptitle("IOPs", fontsize=20)
iopsInit = len(iops.axes)
bw = plot.figure(figsize=(20,15))
bw.suptitle("Bandwidth MB/s", fontsize=20)
bwInit = len(bw.axes)
latency = plot.figure(figsize=(20,15))
latency.suptitle("Latency, MicroSec.", fontsize=20)
latencyInit = len(latency.axes)
xCpu = plot.figure(figsize=(20,15))
xCpu.suptitle("X-ENV Utilization", fontsize=20)
xCpuInit = len(xCpu.axes)
for name in xmsData.dtype.names:
if re.search('iops', name):
drawPlots(xmsData,iops,name,"IOPs",iopsInit+1)
if re.search('bandwidth', name):
drawPlots(xmsData,bw,name,"Bandwidth, MB/s", bwInit+1)
if re.search('latency', name):
drawPlots(xmsData,latency,name,"Latency, MicroSec", latencyInit+1)
for name in xenvData.dtype.names:
drawPlots(xenvData,xCpu,name,"% CPU Utilization", xCpuInit+1)
pdfDoc = PdfPages('XtremPerfcharts.pdf')
pdfDoc.savefig(iops)
pdfDoc.savefig(bw)
pdfDoc.savefig(latency)
pdfDoc.savefig(xCpu)
pdfDoc.close()
plot.close(iops)
plot.close(bw)
plot.close(latency)
plot.close(xCpu)
# plot.show()
def drawVolPerfCharts(vol):
volData = np.genfromtxt('%s.csv' % (vol), dtype=float, delimiter=',', names=True)
plot.ioff()
iops = plot.figure(figsize=(20,15))
iops.suptitle("IOPs", fontsize=20)
iopsInit = len(iops.axes)
bw = plot.figure(figsize=(20,15))
bw.suptitle("Bandwidth MB/s", fontsize=20)
bwInit = len(bw.axes)
latency = plot.figure(figsize=(20,15))
latency.suptitle("Latency, MicroSec.", fontsize=20)
latencyInit = len(latency.axes)
for name in volData.dtype.names:
if re.search('iops', name):
drawPlots(volData,iops,name,"IOPs",iopsInit+1)
if re.search('bandwidth', name):
drawPlots(volData,bw,name,"Bandwidth, MB/s", bwInit+1)
if re.search('latency', name):
drawPlots(volData,latency,name,"Latency, MicroSec", latencyInit+1)
pdfDoc = PdfPages('%s.pdf' %(vol))
pdfDoc.savefig(iops)
pdfDoc.savefig(bw)
pdfDoc.savefig(latency)
pdfDoc.close()
plot.close(iops)
plot.close(bw)
plot.close(latency)
def drawEsxCharts(hostname,storageHba):
pdfDoc = PdfPages('host_%s.pdf'%(hostname))
data = np.genfromtxt('%s.csv' %(hostname), dtype=float, delimiter=',', names=True)
# print data.dtype.names
cpu = plot.figure(figsize=(20,15))
cpu.suptitle("% CPU-Utilization", fontsize=20)
cpuInit = len(cpu.axes)
memory = plot.figure(figsize=(20,15))
memory.suptitle("% Memory Usage", fontsize=20)
memoryInit = len(memory.axes)
for name in data.dtype.names:
if re.match('CPU_Utilization', name):
plotName = '% CPU Util'
drawPlots(data,cpu,name,"% CPU Util",cpuInit+1)
if re.match('Memory_Usage', name):
plotName = '% Usage'
drawPlots(data,memory,name,"% Memory Usage", memoryInit+1)
for hba in storageHba:
hba_iops = plot.figure(figsize=(20,15))
hba_iops.suptitle("%s IOPs"%(hba), fontsize=20)
hbaIopsInit = len(hba_iops.axes)
hba_bw = plot.figure(figsize=(20,15))
hba_bw.suptitle("%s Bandwidth"%(hba), fontsize=20)
hbaBwInit = len(hba_bw.axes)
hba_latency = plot.figure(figsize=(20,15))
hba_latency.suptitle("%s Latency"%(hba), fontsize=20)
hbaLatencyInit = len(hba_latency.axes)
for name in data.dtype.names:
if re.search('Storage_adapter%s'%(hba), name) and re.search('requests_per_second', name):
plotName = '%s IOPs' %(hba)
drawPlots(data,hba_iops,name,"IOPs",hbaIopsInit+1)
if re.search('Storage_adapter%s'%(hba), name) and re.search(r'_rate_average', name):
plotName = 'Bandwidth Utilization'
drawPlots(data,hba_bw,name,"Bandwidth Utilization", hbaBwInit+1)
if re.search('Storage_adapter%s'%(hba), name) and re.search(r'_latency_average', name):
plotName = 'Latency'
drawPlots(data,hba_latency,name,"Latency (msec)", hbaLatencyInit+1)
pdfDoc.savefig(hba_latency)
pdfDoc.savefig(hba_iops)
pdfDoc.savefig(hba_bw)
pdfDoc.savefig(cpu)
pdfDoc.savefig(memory)
pdfDoc.close()
plot.close(hba_iops)
plot.close(hba_bw)
plot.close(hba_latency)
plot.close(cpu)
plot.close(memory)
# plot.show()
def save_as_pdf(self):
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages(os.path.join(self.path, self.name+str(".pdf"))) as pdf:
pdf.savefig()
plt.close()
def plot_profiles_to_file(annot, pntr, ups=200, smooth_param=50):
pp = PdfPages(options.save_path + 'Figures/individual_signals.pdf')
clrs_ = ['red', 'blue', 'black', 'orange', 'magenta', 'cyan']
vec_sense = {}
vec_antisense = {}
# for qq in tq(range(annot.shape[0])):
for qq in tq(range(100)):
chname = annot['chr'].iloc[qq]
if annot['strand'].iloc[qq] == '+':
start = annot['start'].iloc[qq] - ups
stop = annot['end'].iloc[qq]
for key in pntr.keys():
vec_sense[key] = pntr[key][0].get_nparray(chname, start, stop - 1)
vec_antisense[key] = pntr[key][1].get_nparray(chname, start, stop - 1)
xran = np.arange(start, stop)
else:
start = annot['start'].iloc[qq]
stop = annot['end'].iloc[qq] + ups
for key in pntr.keys():
vec_sense[key] = np.flipud(pntr[key][1].get_nparray(chname, start, stop))
vec_antisense[key] = np.flipud(pntr[key][0].get_nparray(chname, start, stop))
xran = np.arange(stop, start, -1)
ax = {}
fig = pl.figure()
pl.title(annot['name'].iloc[qq])
for i, key in enumerate(pntr.keys()):
sm_vec_se = sm.smooth(vec_sense[key], smooth_param)[(smooth_param - 1):-(smooth_param - 1)]
sm_vec_as = sm.smooth(vec_antisense[key], smooth_param)[(smooth_param - 1):-(smooth_param - 1)]
ax[key] = pl.subplot(len(pntr), 1, i+1)
ax[key].plot(xran, vec_sense[key], label=key, color=clrs_[i], alpha=0.5)
ax[key].plot(xran, -vec_antisense[key], color=clrs_[i], alpha=0.5)
ax[key].plot(xran, sm_vec_se, color=clrs_[i], linewidth=2)
ax[key].plot(xran, -sm_vec_as, color=clrs_[i], linewidth=2)
ax[key].legend(loc='upper center', bbox_to_anchor=(0.5, 1.05), fontsize=6, ncol=1)
pp.savefig()
pl.close()
pp.close()
for pn in pntr.values():
pn[0].close()
pn[1].close()