本文整理汇总了Python中matplotlib.pylab.get_current_fig_manager函数的典型用法代码示例。如果您正苦于以下问题:Python get_current_fig_manager函数的具体用法?Python get_current_fig_manager怎么用?Python get_current_fig_manager使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_current_fig_manager函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: multipleBoxPlot
def multipleBoxPlot(DF, variable = "", unit = ""):
DF = DF.dropna()
meds = DF.median()
meds.sort(ascending=False)
DF = DF[meds.index]
columns = DF.columns
figure = plt.figure(figsize=(20, 15))
figure.patch.set_facecolor('white')
for column in columns:
plt.boxplot(DF[columns].values)
xticks(range(1,len(columns) + 1),columns, rotation=90)
if variable != "" and unit != "":
ylabel(variable + " (" + unit + ")")
else:
pass
# Store image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
pylab.close()
img = str((buffer.getvalue()).encode('Base64'))
return img
示例2: outlierDetectionPlot
def outlierDetectionPlot(self,filteredData,variable="",unit=""):
outlierDataPD = filteredData[filteredData['outlier'] == True]
# filteredData[filteredData['outlier'] == True] = np.nan
figure = plt.figure(facecolor='white')
subplot = figure.add_subplot(111)
orginalData, = subplot.plot(filteredData.index.values,filteredData[variable].values,color = 'b')
outlierData = subplot.scatter(outlierDataPD.index.values,outlierDataPD[variable].values,color = 'r')
subplot.set_ylabel(variable +"("+unit+")")
subplot.legend([outlierData],["Outliers"])
subplot.grid()
grid(True)
subplot.xaxis.set_major_locator(MaxNLocator(8))
# Store image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
pylab.close()
img = str((buffer.getvalue()).encode('Base64'))
return img
示例3: scatter_plot
def scatter_plot(self):
sm_value = self.sm_value
ob_value = self.ob_value
figure = plt.figure(facecolor='white')
subplot = figure.add_subplot(111)
index_non_nan = np.isfinite(sm_value) & np.isfinite(ob_value)
fit = np.polyfit(sm_value[index_non_nan],ob_value[index_non_nan],deg = 1)
fx = np.poly1d(fit)
subplot.scatter(sm_value,ob_value)
subplot.plot(sm_value, fx(sm_value), color = 'r')
grid(True)
formatter = DateFormatter('%Y/%m')
subplot.set_xlabel("Simulation")
subplot.set_ylabel("Observation")
subplot.grid()
# Store image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
pylab.close()
img = str((buffer.getvalue()).encode('Base64'))
return img
示例4: in_concentration_graph
def in_concentration_graph(request):
db = [6.0584, 5.65325]
segregationCoefficient = float(request.GET.get('sc'))
concentration = float(request.GET.get('c'))
aWellAlloy = db[int(request.GET.get('wa'))]
wellLength = float(request.GET.get('wl'))
aRightBarrierAlloy = db[int(request.GET.get('rba'))]
rightBarrierLength = float(request.GET.get('rbl'))
latticeParam = aWellAlloy * concentration + aRightBarrierAlloy * (1 - concentration)
wellMonoLayers = int((2 * wellLength) // latticeParam)
rightBarrierMonoLayers = int((2 * rightBarrierLength) // aRightBarrierAlloy)
concentrationInsideWell = lambda n: concentration * (1 - segregationCoefficient ** n)
concentrationOutsideWell = lambda n: concentration * (1 - segregationCoefficient ** n) * (segregationCoefficient ** (n - wellMonoLayers))
gTitle = ''
yTitle = 'In Concentration (%)'
# Get current size
fig_size = rcParams["figure.figsize"]
# Set figure width to 12 and height to 9
fig_size[0] = 12
fig_size[1] = 6
rcParams["figure.figsize"] = fig_size
f, (ax1, ax2) = subplots(1, 2, sharey=True)
layers = [l for l in xrange(1, wellMonoLayers + 1)]
wellPoints = [concentrationInsideWell(n) for n in xrange(1, wellMonoLayers + 1)]
yTitle = "Energy (eV)"
gTitle = "In Concentration Inside Well"
ax1.step(layers, wellPoints, color='green', marker='', linestyle='solid')
ax1.set_title(gTitle)
ax1.set_xlabel("Layer")
ax1.set_ylabel(yTitle)
layers = [l for l in xrange(wellMonoLayers + 1, rightBarrierMonoLayers + 1)]
wellPoints = [concentrationOutsideWell(n) for n in xrange(wellMonoLayers + 1, rightBarrierMonoLayers + 1)]
gTitle = "In Concentration Outside Well"
ax2.step(layers, wellPoints, color='green', marker='', linestyle='solid')
ax2.set_title(gTitle)
ax2.set_xlabel("Layer")
ax2.set_ylabel(yTitle)
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
graphIMG.save(buffer, "PNG")
pylab.close()
return HttpResponse(buffer.getvalue(), content_type="image/png")
示例5: graph
def graph(request):
from matplotlib import pylab
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
x3 = np.linspace(2.0, 4.0)
x4 = np.linspace(0.0, 7.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
y3 = np.cos(2 * np.pi * x2)
y4 = np.cos(2 * np.pi * x2)
plt.subplot(2, 2, 1)
plt.plot(x1, y1, 'yo-',)
plt.title('Temperature')
plt.ylabel('Celcius')
plt.subplot(2, 2, 2)
plt.plot(x3, y3, 'yo-')
plt.title('Druck')
plt.ylabel('Bar')
plt.subplot(2, 2, 4)
plt.plot(x2, y2, 'r.-')
plt.title('4te Variable')
plt.ylabel('unknown')
plt.subplot(2, 2, 3)
plt.plot(x3, y3, 'yo-')
plt.title('Feuchtigkeit')
plt.ylabel('Digits')
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
graphIMG.save(buffer,"PNG")
pylab.close()
return HttpResponse(buffer.getvalue(), mimetype = "image/png")
示例6: residual_analysis
def residual_analysis(self):
dropnan_DF = self.dropnan_DF
model = sm.ols(formula='ob_value ~ sm_value', data=dropnan_DF)
fitted = model.fit()
fittedvalues = np.array(fitted.fittedvalues)
residual = fittedvalues - np.array(dropnan_DF.ob_value)
norm_residual = fitted.resid_pearson
###
figure = plt.figure(facecolor='white')
subplot1 = figure.add_subplot(2,2,1)
subplot1.scatter(fittedvalues,residual)
subplot1.set_xlabel("Fitted values")
subplot1.set_ylabel("Residuals")
subplot1.set_title("Residuals vs Fitted")
subplot2 = figure.add_subplot(2,2,2)
probplot(norm_residual,plot=subplot2)
subplot2.set_title("Normal Q-Q")
subplot2.set_ylabel("Standardized residuals")
subplot2.set_xlabel("Theoretical Quantiles")
subplot3 = figure.add_subplot(2,2,3)
subplot3.scatter(fittedvalues,np.sqrt(np.abs(residual)))
subplot3.set_title("Scale-Location")
subplot3.set_ylabel(r'$\sqrt{\mathrm{|Standardized\/residuals|}}$')
subplot3.set_xlabel("Fitted values")
subplot4 = figure.add_subplot(2,2,4)
norm_residual = (np.matrix(norm_residual)).T
H = norm_residual*(norm_residual.T*norm_residual).I*norm_residual.T
h = H.diagonal()
subplot4.scatter(np.array(h),np.array(norm_residual.T))
subplot4.set_title("Residuals vs Leverage")
subplot4.set_ylabel("Standardized residuals")
subplot4.set_xlabel("Leverage")
subplot4.xaxis.set_major_locator(MaxNLocator(6))
figure.tight_layout()
# Store image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
pylab.close()
img = str((buffer.getvalue()).encode('Base64'))
return img
示例7: history
def history(request):
'''
Creates a matplotlib line chart of the variant history and gives view.
Returns a template of the home view
'''
varHistory = Dspclinva.objects.values_list('date_created')
date_list = []
for items in varHistory:
date_list.append(items[0])
sortDateList = sort(date_list)
dates = matplotlib.dates.date2num(sortDateList)
counts = defaultdict(int)
for item in dates:
counts[item] += 1
allDates = []
allValues = []
for key, value in counts.iteritems():
allDates.append(key)
allValues.append(value)
addedValues = []
for index, elem in enumerate(allValues):
if index == 0:
temp = elem
addedValues.append(temp)
else:
temp += elem
addedValues.append(temp)
sortDates = sort(allDates)
x = sortDates
y = addedValues
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
yearsFmt = mdates.DateFormatter('%Y')
fig, ax = plt.subplots()
ax.plot(x,y)
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
fig.autofmt_xdate()
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
graphIMG.save(buffer, "PNG")
pylab.close()
return HttpResponse(buffer.getvalue(), content_type="image/png")
示例8: plot_init
def plot_init(data):
"""Initialize plot.
Args:
data: team matrix
"""
# Set figure style
sns.set_style("dark")
# Create subplot grid
fig = gridspec.GridSpec(2, 1)
# Create subplots
axarr = [plt.subplot(fig[0, 0]), plt.subplot(fig[1, 0])]
# Plot data
img = axarr[0].imshow(data, interpolation = 'nearest', cmap = plt.cm.ocean,
extent = (0.5, np.shape(data)[0] + 0.5, 0.5,
np.shape(data)[1] + 0.5))
# Display round
plt.title("Current Round:" + str(0))
# Set labels
axarr[0].set_ylabel("Give")
axarr[0].set_xlabel("Accept")
axarr[0].set_title("Distribution of Teams")
# Plot average deal data
axarr[1].plot(avg_deal_data)
# Set labels
axarr[1].set_xlim(0,rounds)
axarr[1].set_ylabel("Average Cash per Deal")
axarr[1].set_xlabel("Round Number")
# Create colorbar for strategy distribution
plt.colorbar(img, ax=axarr[0], label= "Prevalence vs. Uniform")
# Interactive mode
plt.ion()
# Changed this to use 'normal' instead of 'zoomed' since it didn't work on
# my system
mng = plt.get_current_fig_manager()
mng.window.state('normal')
# Display everything
plt.show()
return fig, axarr
示例9: fit_pressures
def fit_pressures(target_sensor):
conn = psycopg2.connect("dbname=will user=levlab host=levlabserver2.stanford.edu")
cur = conn.cursor()
sensor_query = '''SELECT {0}.name FROM {0} WHERE {0}.fault=FALSE and {0}.unit='Torr';'''.format(GAUGE_TABLE)
cur.execute(sensor_query)
sensors = cur.fetchall()
databysensors = dict()
notesbysensors = dict()
for sensor in sensors:
sensorname = sensor[0]
data_query = '''SELECT {0}.time, {0}.value FROM {0}, {1} WHERE {0}.value > 0 and {0}.id = {1}.id and {1}.name = %s and {1}.unit='Torr' and {0}.time > %s;'''.format(PRESSURES_TABLE, GAUGE_TABLE)
annotate_query = '''SELECT {0}.note, {0}.time, {0}.pressure FROM {0}, {1} WHERE {1}.name = %s and {0}.sensorid={1}.id'''.format(ANNOTATIONS_TABLE, GAUGE_TABLE)
cur.execute(data_query, (sensorname, STARTDATETIME,))
databysensors[sensorname]=cur.fetchall()
cur.execute(annotate_query, (sensorname,))
notesbysensors[sensorname]=cur.fetchall()
cur.close()
conn.close()
time = [data[0] for data in databysensors[target_sensor]]
time_secs = np.array([(t - STARTDATETIME).total_seconds() for t in time])
value = np.array([float(data[1]) for data in databysensors[target_sensor]])
p0 = np.array([P_FINAL, value[0] - P_FINAL, tau_guess])
popt, _ = optimize.curve_fit(exp_func, time_secs, value, p0)
print popt
fit_result = [exp_func(t, *popt) for t in time_secs]
if P_FINAL > popt[0]:
est_pumpdown = STARTDATETIME + datetime.timedelta(seconds = popt[2] * np.log(popt[1] / (P_FINAL - popt[0])))
print est_pumpdown
else:
print 'Desired pressure is unreachable.'
one_wk_from_now_secs = ((datetime.datetime.now() - STARTDATETIME) + datetime.timedelta(weeks=1)).total_seconds()
print 'Pressure in one week is: %e'%(exp_func(one_wk_from_now_secs, *popt))
fig = plt.figure(figsize=(12,6))
ax1 = fig.add_subplot(111)
# ax1.set_yscale('log')
ax1.plot_date(time, value,'-', label = sensor[0])
ax1.plot_date(time, fit_result, '-', label='Fit Result')
ax1.fmt_xdate = pltdates.DateFormatter('%H%M')
ax1.legend(loc = 'lower left')
ax1.set_xlabel('Time')
ax1.set_ylabel('Pressure / Torr')
fig.autofmt_xdate()
wm = plt.get_current_fig_manager()
wm.window.wm_geometry("1920x1080+50+50")
plt.show()
示例10: graph_in_endcode64
def graph_in_endcode64(DF,variable="",unit="", title = "", linear_regression = False):
DateTime = pandas.to_datetime(DF.index.values)
data = np.array(DF.values)
figure = plt.figure(facecolor='white')
subplot = figure.add_subplot(111)
# Construct the graph
subplot.plot(DateTime, data, linewidth=1.0)
if variable != "" and unit != "":
subplot.set_xlabel('DateTime')
subplot.set_ylabel(variable + " (" + unit + ")")
else:
pass
if title != "":
subplot.set_title(title)
if linear_regression == True:
index_non_nan = np.isfinite(data)
x = np.array(mpl.dates.date2num(list(DateTime)))
z = np.polyfit(x[index_non_nan],data[index_non_nan],1)
p = np.poly1d(z)
subplot.plot(DateTime,p(x),'r')
else:
pass
formatter = DateFormatter('%m/%Y')
subplot.grid(True)
subplot.xaxis.set_major_formatter(formatter)
subplot.xaxis.set_major_locator(MaxNLocator(8))
# figure.autofmt_xdate()
# Store image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
pylab.close()
img = str((buffer.getvalue()).encode('Base64'))
return img
示例11: update_plots
def update_plots(self, atoms):
"""Update the coverage and TOF plots."""
# fetch data piggy-backed on atoms object
new_time = atoms.kmc_time
occupations = atoms.occupation.sum(axis=1) / lattice.spuck
tof_data = atoms.tof_data
# store locally
while len(self.times) > getattr(settings, 'hist_length', 30):
self.tof_hist.pop(0)
self.times.pop(0)
self.occupation_hist.pop(0)
self.times.append(atoms.kmc_time)
self.tof_hist.append(tof_data)
self.occupation_hist.append(occupations)
# plot TOFs
for i, tof_plot in enumerate(self.tof_plots):
tof_plot.set_xdata(self.times)
tof_plot.set_ydata([tof[i] for tof in self.tof_hist])
self.tof_diagram.set_xlim(self.times[0], self.times[-1])
self.tof_diagram.set_ylim(1e-3,
10 * max([tof[i] for tof in self.tof_hist]))
# plot occupation
for i, occupation_plot in enumerate(self.occupation_plots):
occupation_plot.set_xdata(self.times)
occupation_plot.set_ydata(
[occ[i] for occ in self.occupation_hist])
max_occ = max(occ[i] for occ in self.occupation_hist)
self.occupation_diagram.set_ylim([0, max(1, max_occ)])
self.occupation_diagram.set_xlim([self.times[0], self.times[-1]])
self.data_plot.canvas.draw_idle()
manager = plt.get_current_fig_manager()
if hasattr(manager, 'toolbar'):
toolbar = manager.toolbar
if hasattr(toolbar, 'set_visible'):
toolbar.set_visible(False)
plt.show()
# [:] is necessary so that it copies the
# values and doesn't reinitialize the pointer
self.time = new_time
return False
示例12: graph
def graph(request):
x=[1,2,3,4,5,6]
y=[5,2,6,8,2,7]
plot(x,y,linewidth=2)
xlabel('x axis')
ylabel('y axis')
title('sample graph')
grid(True)
buffer=StringIO.StringIO()
canvas=pylab.get_current_fig_manager().canvas
canvas.draw()
graphIMG=PIL.Image.fromstring('RGB',canvas.get_width_height(),canvas.tostring_rgb())
graphIMG.save(buffer,'PNG')
pylab.close()
return HttpResponse(buffer.getvalue(),content_type='image/png')
示例13: maximize_fig
def maximize_fig(fig=None):
"""
Try to set the figure fullscreen
"""
if fig and "canvas" in dir(fig) and fig.canvas:
if "Qt4" in pylab.get_backend():
fig.canvas.setWindowState(QtCore.Qt.WindowMaximized)
else:
mng = pylab.get_current_fig_manager()
# attempt to maximize the figure ... lost hopes.
win_shape = (1920, 1080)
event = Event(*win_shape)
try:
mng.resize(event)
except TypeError:
mng.resize(*win_shape)
update_fig(fig)
示例14: multi_timeserise_plot
def multi_timeserise_plot(self):
DF = self.DF
datetime = np.array(DF.index.values)
figure = plt.figure(facecolor='white')
print "testn"
i = 0
n_colums = (DF.shape)[1]
for e in DF:
try:
if i == 0:
subplot0 = figure.add_subplot(n_colums,1,1+i)
plot0, = subplot0.plot(datetime,DF[e])
subplot0.legend([str(e)],prop={'size':7})
subplot0.xaxis.set_major_locator(MaxNLocator(6))
subplot0.yaxis.set_major_locator(MaxNLocator(4))
setp(subplot0.get_xticklabels(), visible=False)
else:
subplot = figure.add_subplot(n_colums,1,1+i,sharex=subplot0)
plot, = subplot.plot(datetime,DF[e])
subplot.legend( [str(e)],prop={'size':7})
subplot.xaxis.set_major_locator(MaxNLocator(6))
subplot.yaxis.set_major_locator(MaxNLocator(4))
if i + 1 == n_colums:
setp(subplot.get_xticklabels(), visible=True)
else:
setp(subplot.get_xticklabels(), visible=False)
except Exception as inst:
print type(inst) # the exception instance
print inst.args # arguments stored in .args
print inst
i = i + 1
# Store image in a string buffer
buffer = StringIO.StringIO()
canvas = pylab.get_current_fig_manager().canvas
canvas.draw()
pilImage = PIL.Image.frombytes("RGB", canvas.get_width_height(), canvas.tostring_rgb())
pilImage.save(buffer, "PNG")
pylab.close()
img = str((buffer.getvalue()).encode('Base64'))
return img
示例15: _set_windowtitle
def _set_windowtitle(self,title):
"""
Helper function to set the title (if not None) of this PyLab plot window.
"""
# At the moment, PyLab does not offer a window-manager-independent
# means for controlling the window title, so what we do is to try
# what should work with Tkinter, and then suppress all errors. That
# way we should be ok when rendering to a file-based backend, but
# will get nice titles in Tk windows. If other toolkits are in use,
# the title can be set here using a similar try/except mechanism, or
# else there can be a switch based on the backend type.
if title is not None:
try:
manager = plt.get_current_fig_manager()
manager.window.title(title)
except:
pass