本文整理汇总了Python中matplotlib.figure.Figure类的典型用法代码示例。如果您正苦于以下问题:Python Figure类的具体用法?Python Figure怎么用?Python Figure使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Figure类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plotSolarRadiationAgainstMonth
def plotSolarRadiationAgainstMonth(filename):
trainRowReader = csv.reader(open(filename, 'rb'), delimiter=',')
month_most_common_list = []
Solar_radiation_64_list = []
for row in trainRowReader:
month_most_common = row[3]
Solar_radiation_64 = row[6]
month_most_common_list.append(month_most_common)
Solar_radiation_64_list.append(Solar_radiation_64)
#convert all elements in the list to float while skipping the first element for the 1st element is a description of the field.
month_most_common_list = [float(i) for i in prepareList(month_most_common_list)[1:] ]
Solar_radiation_64_list = [float(i) for i in prepareList(Solar_radiation_64_list)[1:] ]
fig=Figure()
ax=fig.add_subplot(111)
title='Scatter Diagram of solar radiation against month of the year'
ax.set_xlabel('Most common month')
ax.set_ylabel('Solar Radiation')
fig.suptitle(title, fontsize=14)
try:
ax.scatter(month_most_common_list, Solar_radiation_64_list)
#it is possible to make other kind of plots e.g bar charts, pie charts, histogram
except ValueError:
pass
canvas = FigureCanvas(fig)
canvas.print_figure('solarRadMonth.png',dpi=500)
示例2: __get_column_width
def __get_column_width(self):
max_length = 0
max_column_text = ''
flag = self.prefs.get('legend_numbers',True)
unit = self.prefs.get('legend_unit',False)
for label,num in self.labels:
if not flag: num = None
if num is not None:
column_length = len(str(label)+str(num)) + 1
else:
column_length = len(str(label)) + 1
if column_length > max_length:
max_length = column_length
if flag:
if type(num) == types.IntType or type(num) == types.LongType:
numString = str(num)
else:
numString = "%.1f" % float(num)
max_column_text = '%s %s' % (str(label),numString)
if unit:
max_column_text += "%"
else:
max_column_text = '%s ' % str(label)
figure = Figure()
canvas = FigureCanvasAgg(figure)
dpi = self.prefs['dpi']
figure.set_dpi( dpi )
l_size,l_padding = self.__get_legend_text_size()
self.text_size = pixelToPoint(l_size,dpi)
text = Text(0.,0.,text=max_column_text,size=self.text_size)
text.set_figure(figure)
bbox = text.get_window_extent(canvas.get_renderer())
self.column_width = bbox.width+6*l_size
示例3: init_window
def init_window(self):
if self.window:
return
self.window = Gtk.Window(title="Subplot Configuration Tool")
try:
self.window.window.set_icon_from_file(window_icon)
except Exception:
# we presumably already logged a message on the
# failure of the main plot, don't keep reporting
pass
self.vbox = Gtk.Box()
self.vbox.set_property("orientation", Gtk.Orientation.VERTICAL)
self.window.add(self.vbox)
self.vbox.show()
self.window.connect('destroy', self.destroy)
toolfig = Figure(figsize=(6, 3))
canvas = self.figure.canvas.__class__(toolfig)
toolfig.subplots_adjust(top=0.9)
SubplotTool(self.figure, toolfig)
w = int(toolfig.bbox.width)
h = int(toolfig.bbox.height)
self.window.set_default_size(w, h)
canvas.show()
self.vbox.pack_start(canvas, True, True, 0)
self.window.show()
示例4: __init__
def __init__(self, viewer, selected):
self.selected = selected
self.ids = [str(i) + " - " + str(s) for i, s in enumerate(selected)]
t2 = Tk.Toplevel(viewer)
t2.title('Data Range Editor')
t2.transient(viewer)
# Image selection combobox
sel_fr = Tk.Frame(master=t2)
Tk.Label(sel_fr, text="Image:").pack(side=Tk.LEFT)
self.imagesel = ttk.Combobox(sel_fr)
self.imagesel['values'] = [str(s) for s in selected]
self.imagesel.bind('<<ComboboxSelected>>', self.update)
im = self.selected[0]
self.imagesel.set(self.ids[0])
self.imagesel.pack(side=Tk.LEFT)
sel_fr.pack(side=Tk.TOP)
# Grid showing current vmin, vmax and original vmin,vmax
lim_fr = Tk.Frame(master=t2)
Tk.Label(lim_fr, text="Upper limit:").grid(row=1,column=1)
Tk.Label(lim_fr, text="Lower limit:").grid(row=2,column=1)
self.ulim_orig, self.llim_orig = Tk.StringVar(), Tk.StringVar()
self.ulim, self.llim = Tk.StringVar(), Tk.StringVar()
self.upper_limit = Tk.Entry(lim_fr, textvariable=self.ulim)
self.lower_limit = Tk.Entry(lim_fr, textvariable=self.llim)
self.upper_limit.grid(row=1,column=2)
self.lower_limit.grid(row=2,column=2)
upper_limit_orig = Tk.Entry(lim_fr, textvariable=self.ulim_orig, state=Tk.DISABLED)
lower_limit_orig = Tk.Entry(lim_fr, textvariable=self.llim_orig, state=Tk.DISABLED)
upper_limit_orig.grid(row=1,column=3)
lower_limit_orig.grid(row=2,column=3)
lim_fr.pack(side=Tk.BOTTOM, fill=Tk.NONE, expand=0)
# Button frame
buttons = Tk.Frame(master=t2)
self.all_images = Tk.BooleanVar()
self.all_images.set(False)
Tk.Checkbutton(buttons, text="Apply to all images", variable=self.all_images).pack(side=Tk.TOP)
apply = Tk.Button(master=buttons, text='Apply', command=self.set_limits)
apply.pack(side=Tk.RIGHT)
reset = Tk.Button(master=buttons, text='Reset', command=self.reset)
reset.pack(side=Tk.RIGHT)
buttons.pack(side=Tk.BOTTOM, fill=Tk.NONE, expand=0)
# Matplotlib figure
f = Figure(figsize=(5,4), dpi=100)
self.a = f.add_subplot(111)
self.canvas = FigureCanvasTkAgg(f, master=t2)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
self.update()
示例5: WattrGraphPanel
class WattrGraphPanel( WattrGUI.GraphPanel ):
subplot = 0
plots = {}
def __init__(self, parent, fgsize=None, dpi=None):
super(WattrGraphPanel, self).__init__(parent)
self.figure = Figure(fgsize, dpi)
#Transparent figure face color
self.figure.set_facecolor((0,0,0,0,))
self.canvas = FigureCanvasWxAgg(self, -1, self.figure)
# Now put all into a sizer
sizer = self.GetSizer()
# This way of adding to sizer allows resizing
sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW)
# Best to allow the toolbar to resize!
self.toolbar = NavigationToolbar2Wx(self.canvas)
self.toolbar.Realize()
sizer.Add(self.toolbar, 0, wx.GROW)
self.Fit()
def add_plot(self, x=1, y=1):
self.subplot += 1
plot = self.figure.add_subplot(x, y, self.subplot)
plot.ticklabel_format(axis='y', style='plain', useOffset=False)
plot.ticklabel_format(axis='x', style='plain', useOffset=False)
self.plots[self.subplot] = plot
return plot
def draw(self):
self.canvas.draw()
示例6: addedRecently
def addedRecently(self, numdays=30, attr='created'):
self.calcStats()
days = {}
fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
limit = self.endOfDay - (numdays) * 86400
res = self.deck.s.column0("select %s from cards where %s >= %f" %
(attr, attr, limit))
for r in res:
d = int((r - self.endOfDay) / 86400.0)
days[d] = days.get(d, 0) + 1
self.addMissing(days, -numdays+1, 0)
graph = fig.add_subplot(111)
intervals = self.unzip(days.items())
if attr == 'created':
colour = addedC
else:
colour = firstC
self.varGraph(graph, numdays, colour, *intervals)
graph.set_xlim(xmin=-numdays+1, xmax=1)
graph.set_xlabel("Day (0 = today)")
if attr == 'created':
graph.set_ylabel("Cards Added")
else:
graph.set_ylabel("Cards First Answered")
return fig
示例7: graph_prices
def graph_prices(x, y, gname):
'''make a plot of the prices over time for a specific game'
x is be the dates of the bins
y is the prices
gname is the name of the game
'''
x_list = list(x)
x_dt = [datetime.fromtimestamp(xx) for xx in x_list]
fig=Figure(facecolor='white')
ax=fig.add_subplot(111)
ax.plot(x_dt,y,'r-')
ax.set_ylim([0,np.max(y) + np.max(y) * 0.10])
#ax.set_title(gname)
#ax.set_axis_bgcolor('red')
formatter = FuncFormatter(money_format)
ax.yaxis.set_major_formatter(formatter)
#fig.autofmt_xdate()
#xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
#ax.xaxis.set_major_formatter(xfmt)
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
canvas=FigureCanvas(fig)
png_output = StringIO.StringIO()
canvas.print_png(png_output)
response=make_response(png_output.getvalue())
response.headers['Content-Type'] = 'image/png'
return response
示例8: DevPlot
class DevPlot(Plot):
def __init__(self,k1={'intel_snb' : ['intel_snb','intel_snb','intel_snb']},k2={'intel_snb':['LOAD_1D_ALL','INSTRUCTIONS_RETIRED','LOAD_OPS_ALL']},processes=1,**kwargs):
self.k1 = k1
self.k2 = k2
super(DevPlot,self).__init__(processes=processes,**kwargs)
def plot(self,jobid,job_data=None):
self.setup(jobid,job_data=job_data)
cpu_name = self.ts.pmc_type
type_name=self.k1[cpu_name][0]
events = self.k2[cpu_name]
ts=self.ts
n_events = len(events)
self.fig = Figure(figsize=(8,n_events*2+3),dpi=110)
do_rate = True
scale = 1.0
if type_name == 'mem':
do_rate = False
scale=2.0**10
if type_name == 'cpu':
scale=ts.wayness*100.0
for i in range(n_events):
self.ax = self.fig.add_subplot(n_events,1,i+1)
self.plot_lines(self.ax, [i], 3600., yscale=scale, do_rate = do_rate)
self.ax.set_ylabel(events[i],size='small')
self.ax.set_xlabel("Time (hr)")
self.fig.subplots_adjust(hspace=0.5)
#self.fig.tight_layout()
self.output('devices')
示例9: plot_activity
def plot_activity(values):
daysFmt = DateFormatter("%d-%B %H:00")
fig=Figure()
ax=fig.add_subplot(111)
times = values.keys()
times.sort()
number_found = [values[key] for key in times]
ax.plot_date(times, number_found, '-')
#assert 0, '%s'%(values)
# format the ticks
ax.xaxis.set_major_locator(HourLocator(byhour=range(0,24,4)))
ax.xaxis.set_major_formatter(daysFmt)
ax.autoscale_view()
ax.grid(True)
ax.set_title('All devices')
fig.autofmt_xdate()
canvas=FigureCanvas(fig)
response=HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
示例10: player_wp
def player_wp(request, code):
try:
player = Player.objects.get(code=code)
except Player.DoesNotExist:
raise Http404
points = player.weekly_points.values_list('points', flat=True)
response = HttpResponse(content_type='image/png')
if points:
weeks = list(player.weekly_points.values_list('week', flat=True))
fig = Figure(figsize=(0.4 * min(max(10, weeks[-1]), 22), 3),
dpi=100, facecolor='white')
ax = fig.add_subplot(111)
rects = ax.bar(weeks, points, align='center', linewidth=1, color='#008ad1', width=1)
ax.set_xlabel("Week")
ax.set_ylabel("Points")
ax.set_xticks(weeks) # add a tick for every week
for p, rect in zip(points, rects):
if p != 0:
if p < 0:
h = p * 2 - 1
elif p > 0:
h = p + 1
ax.text(rect.get_x() + rect.get_width() / 2., h, str(p),
fontsize=10, color='black', ha='center')
ax.set_xlim((0.5, max(10, weeks[-1]) + 0.5))
else:
fig = Figure(figsize=(1, 1), dpi=1, facecolor='white') # return one white pixel
canvas = FigureCanvas(fig)
canvas.print_png(response)
return response
示例11: __init__
def __init__(self):
c = 3.0e+11 # speed of light, um/ms
cs = 2.8e-11 # cross section, um^2
n = 1.5
self.WI = (c/n)*cs # 18.0, um^3/ms
self.Nv = 5.0e+7 # 5.0e+7 1/um^3 - density of active particles
self.W2 = 1./0.23 # 1/ms - 1/spontaneous emission lifetime (2->1 transitions)
self.W3 = 1.e-3*self.W2 # 1/ms - 1/spontaneous emission lifetime (3->2 transitions)
self.eta = 1.e-16
tb, te, self.ts = 0.0, 1.0, 1.0e-4
self.x = arange(tb,te,self.ts)
self.Np = len(self.x)
self.y1 = ndarray(shape=(self.Np), dtype='float')
self.y2 = ndarray(shape=(self.Np), dtype='float')
# self.y3 = ndarray(shape=(self.Np), dtype='float')
self.y4 = ndarray(shape=(self.Np), dtype='float')
self.PlotWindow = Tk.Toplevel()
self.PlotWindow.title('numerical simulation of kinetic equations')
fig = Figure(figsize=(10,6), dpi=100)
self.g1 = fig.add_subplot(211)
self.g2 = fig.add_subplot(212)
self.canvas = FigureCanvasTkAgg(fig, self.PlotWindow)
self.canvas.show()
self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
self.toolbar = NavigationToolbar2TkAgg( self.canvas, self.PlotWindow)
self.canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
示例12: save
def save(self, name, log=False, vrange=None):
if self.imdict['X'].sum() == 0.0 and log:
warn("can't plot {}, in log mode".format(name), RuntimeWarning,
stacklevel=2)
return
fig = Figure(figsize=(8,6))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(1,1,1)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", "5%", pad="1.5%")
if log:
norm=LogNorm()
else:
norm=Normalize()
if vrange:
self.imdict['vmin'], self.imdict['vmax'] = vrange
im = ax.imshow(norm=norm,**self.imdict)
cb_dict = {'cax':cax}
if log:
cb_dict['ticks'] = LogLocator(10, np.arange(0.1,1,0.1))
cb_dict['format'] = LogFormatterMathtext(10)
try:
cb = plt.colorbar(im, **cb_dict)
except ValueError:
print self.imdict['X'].sum()
raise
ax.set_xlabel(self.x_label, x=0.98, ha='right')
ax.set_ylabel(self.y_label, y=0.98, ha='right')
if self.cb_label:
cb.set_label(self.cb_label, y=0.98, ha='right')
canvas.print_figure(name, bbox_inches='tight')
示例13: TestDialog
class TestDialog( QDialog, Ui_dlgMPLTest ):
def __init__( self, parent = None ):
super( TestDialog, self ).__init__( parent )
self.setupUi( self )
# initialize mpl plot
self.figure = Figure()
#self.figure.set_figsize_inches( ( 4.3, 4.2 ) )
self.axes = self.figure.add_subplot( 111 )
self.figure.suptitle( "Frequency distribution", fontsize = 12 )
self.axes.grid( True )
self.canvas = FigureCanvas( self.figure )
layout = QVBoxLayout()
self.widgetPlot.setLayout(layout)
layout.addWidget(self.canvas)
#self.canvas.setParent( self.widgetPlot )
# draw mpl plot
#self.axes.clear()
#self.axes.grid( True )
#self.figure.suptitle( "Frequency distribution", fontsize = 12 )
self.axes.set_ylabel( "Count", fontsize = 8 )
self.axes.set_xlabel( "Values", fontsize = 8 )
x = [ 4, 1, 5, 3, 3, 2, 3, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1 ]
n, bins, pathes = self.axes.hist( x, 18, alpha=0.5, histtype = "bar" )
self.canvas.draw()
self.setWindowTitle( self.tr( "MPL test" ) )
示例14: plot_sfh
def plot_sfh(model_sfh, mock_sfh, plot_path):
labels = {'lewis': r'ACS-MS', 'oir_all': r'OIR-ALL'}
colors = {'lewis': 'dodgerblue', 'oir_all': 'maroon'}
fig = Figure(figsize=(3.5, 3.5), frameon=False)
canvas = FigureCanvas(fig)
gs = gridspec.GridSpec(1, 1,
left=0.18, right=0.95, bottom=0.15, top=0.95,
wspace=None, hspace=None,
width_ratios=None, height_ratios=None)
ax = fig.add_subplot(gs[0])
for plane_key in ['lewis', 'oir_all']:
if plane_key not in model_sfh['sfh'].keys():
continue
plot_single_sfh_line(ax, model_sfh['sfh'][plane_key],
label=labels[plane_key],
color=colors[plane_key],
drawstyle='steps-mid')
_plot_mean_age(ax, model_sfh['sfh'][plane_key].attrs['mean_age'],
c=colors[plane_key])
# plot_single_sfh_line(ax, model_sfh, label='Model', color='k')
# print model_sfh['sfr']
_plot_mock_sfh(ax, mock_sfh, lw=1.5, c='k', label='Mock')
_plot_mean_age(ax, mock_sfh.attrs['mean_age'])
ax.legend(loc='lower left', fontsize=8, frameon=True)
gs.tight_layout(fig, pad=1.08, h_pad=None, w_pad=None, rect=None)
canvas.print_figure(plot_path + ".pdf", format="pdf")
示例15: nextDue
def nextDue(self, days=30):
self.calcStats()
fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
graph = fig.add_subplot(111)
dayslists = [self.stats['next'], self.stats['daysByType']['mature']]
for dayslist in dayslists:
self.addMissing(dayslist, self.stats['lowestInDay'], days)
argl = []
for dayslist in dayslists:
dl = [x for x in dayslist.items() if x[0] <= days]
argl.extend(list(self.unzip(dl)))
self.varGraph(graph, days, [dueYoungC, dueMatureC], *argl)
cheat = fig.add_subplot(111)
b1 = cheat.bar(0, 0, color = dueYoungC)
b2 = cheat.bar(1, 0, color = dueMatureC)
cheat.legend([b1, b2], [
"Young",
"Mature"], loc='upper right')
graph.set_xlim(xmin=self.stats['lowestInDay'], xmax=days+1)
graph.set_xlabel("Day (0 = today)")
graph.set_ylabel("Cards Due")
return fig