本文整理汇总了Python中matplotlib.ticker.ScalarFormatter类的典型用法代码示例。如果您正苦于以下问题:Python ScalarFormatter类的具体用法?Python ScalarFormatter怎么用?Python ScalarFormatter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ScalarFormatter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: quickPlot
def quickPlot(filename, path, datalist, xlabel="x", ylabel="y", xrange=["auto", "auto"], yrange=["auto", "auto"], yscale="linear", xscale="linear", col=["r", "b"]):
"""Plots Data to .pdf File in Plots Folder Using matplotlib"""
if "plots" not in os.listdir(path):
os.mkdir(os.path.join(path, "plots"))
coltab = col*10
seaborn.set_context("notebook", rc={"lines.linewidth": 1.0})
formatter = ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-2, 3))
fig = Figure(figsize=(6, 6))
ax = fig.add_subplot(111)
for i, ydata in enumerate(datalist[1:]):
ax.plot(datalist[0], ydata, c=coltab[i])
ax.set_title(filename)
ax.set_yscale(yscale)
ax.set_xscale(xscale)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if xrange[0] != "auto":
ax.set_xlim(xmin=xrange[0])
if xrange[1] != "auto":
ax.set_xlim(xmax=xrange[1])
if yrange[0] != "auto":
ax.set_ylim(ymin=yrange[0])
if yrange[1] != "auto":
ax.set_ylim(ymax=yrange[1])
if yscale == "linear":
ax.yaxis.set_major_formatter(formatter)
ax.xaxis.set_major_formatter(formatter)
canvas = FigureCanvasPdf(fig)
canvas.print_figure(os.path.join(path, "plots", filename+".pdf"))
return
示例2: funcPlotEnd
def funcPlotEnd(fig, ax, theme, width, height, x_showTicks=True, x_showTickLabels=True, y_showTicks=True, y_showTickLabels=True, drawAxis=True, showGrid=True):
""" set some layout options """
if not x_showTicks:
ax.set_xticks([])
if not x_showTickLabels:
ax.set_xticklabels([])
else:
xfmt = ScalarFormatter(useMathText=True)
xfmt.set_powerlimits((-2,3))
ax.xaxis.set_major_formatter(xfmt)
if not y_showTicks:
ax.set_yticks([])
if not y_showTickLabels:
ax.set_yticklabels([])
ax.grid(showGrid, which="both", color=theme.getGridColor(), linestyle="-")
ax.patch.set_facecolor(theme.getBackgroundColor())
if drawAxis:
axisColor = theme.getGridColor()
else:
axisColor = theme.getBackgroundColor()
ax.spines["bottom"].set_color(axisColor)
ax.spines["top"].set_color(axisColor)
ax.spines["right"].set_color(axisColor)
ax.spines["left"].set_color(axisColor)
ax.tick_params(axis="x", colors=theme.getGridColor(), which="both", labelsize=theme.getFontSize())
ax.tick_params(axis="y", colors=theme.getGridColor(), which="both", labelsize=theme.getFontSize())
ax.xaxis.label.set_color(theme.getFontColor())
ax.yaxis.label.set_color(theme.getFontColor())
[x_ticklabel.set_color(theme.getFontColor()) for x_ticklabel in ax.get_xticklabels()]
[y_ticklabel.set_color(theme.getFontColor()) for y_ticklabel in ax.get_yticklabels()]
fig.set_size_inches(width, height)
示例3: age_vs_plot
def age_vs_plot(track, infile, ycol='logl', ax=None, annotate=True, xlabels=True,
save_plot=True, ylabels=True):
agb_mix = infile.agb_mix
set_name = infile.set_name
if ycol == 'logl':
ydata= track.get_col('L_star')
majL = MultipleLocator(.2)
minL = MultipleLocator(.1)
ylab = '$\log\ L_{\odot}$'
elif ycol == 'logt':
ydata = track.get_col('T_star')
majL = MultipleLocator(.1)
minL = MultipleLocator(.05)
ylab = '$\log\ Te$'
elif ycol == 'C/O':
ydata = track.get_col('CO')
majL = MaxNLocator(4)
minL = MaxNLocator(2)
ylab = '$C/O$'
else:
print 'logl, logt, C/O only choices for y.'
return
age = track.get_col('ageyr')
addpt = track.addpt
Qs = list(track.Qs)
if ax is None:
fig, ax = plt.subplots()
ax.plot(age, ydata, color='black')
ax.plot(age[Qs], ydata[Qs], 'o', color='green')
if len(addpt) > 0:
ax.plot(age[addpt], ydata[addpt], 'o', color='purple')
ax.yaxis.set_major_locator(majL)
ax.yaxis.set_minor_locator(minL)
majorFormatter = ScalarFormatter()
majorFormatter.set_powerlimits((-3, 4))
ax.xaxis.set_major_formatter(majorFormatter)
if annotate is True:
ax.text(0.06, 0.87, '${\\rm %s}$' % agb_mix.replace('_', '\ '),
transform=ax.transAxes)
ax.text(0.06, 0.77,'${\\rm %s}$' % set_name.replace('_', '\ '),
transform=ax.transAxes)
ax.text(0.06, 0.67, '$M=%.2f$' % track.mass,
transform=ax.transAxes)
if ylabels is True:
ax.set_ylabel('$%s$' % ylab, fontsize=20)
if xlabels is True:
ax.set_xlabel('$\rm{Age (yr)}$', fontsize=20)
if save_plot is True:
plotpath = os.path.join(infile.diagnostic_dir, 'age_v/')
fileIO.ensure_dir(plotpath)
fname = os.path.split(track.name)[1].replace('.dat', '')
fig_name = os.path.join(plotpath, '_'.join(('diag', fname)))
plt.savefig('%s_age_v.png' % fig_name, dpi=300)
plt.close()
return
示例4: set_arbitrary_ticks
def set_arbitrary_ticks(ax,axis,events,index1,index2,fontsize=10,fontname='sans'):
"""
if an axis is using an unknown scale or we just with to use the data to scale
the axis
"""
buff = 0.02
formatter = ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-3,3))
## handle data edge buffers
if axis in ['x','both']:
bufferX = buff * (events[:,index1].max() - events[:,index1].min())
ax.set_xlim([events[:,index1].min()-bufferX,events[:,index1].max()+bufferX])
ax.xaxis.set_major_formatter(formatter)
if axis in ['y','both']:
bufferY = buff * (events[:,index2].max() - events[:,index2].min())
ax.set_ylim([events[:,index2].min()-bufferY,events[:,index2].max()+bufferY])
ax.yaxis.set_major_formatter(formatter)
if axis in ['x','both']:
for tick in ax.xaxis.get_major_ticks():
tick.label.set_fontsize(fontsize-2)
tick.label.set_fontname(fontname)
if axis in ['y','both']:
for tick in ax.yaxis.get_major_ticks():
tick.label.set_fontsize(fontsize-2)
tick.label.set_fontname(fontname)
示例5: __init__
def __init__(self, ndec=None, useOffset=True, useMathText=False):
ScalarFormatter.__init__(self, useOffset, useMathText)
if ndec is None or ndec < 0:
self.format = None
elif ndec == 0:
self.format = "%d"
else:
self.format = "%%1.%if" % ndec
示例6: get_colorbar_formatter
def get_colorbar_formatter(varname):
if varname in ["STFL", "STFA"]:
return None
else:
# format the colorbar tick labels
sfmt = ScalarFormatter(useMathText=True)
sfmt.set_powerlimits((-3, 3))
return sfmt
示例7: AbsFormatter
class AbsFormatter(object):
def __init__(self, useMathText=True):
self._fmt = ScalarFormatter(useMathText=useMathText, useOffset=False)
self._fmt.create_dummy_axis()
def __call__(self, direction, factor, values):
self._fmt.set_locs(values)
return [self._fmt(abs(v)) for v in values]
示例8: setAxes
def setAxes(ax):
globalAxesSettings(ax)
ax.yaxis.set_major_locator(MaxNLocator(4))
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.yaxis.set_minor_locator(AutoMinorLocator(2))
f = ScalarFormatter(useMathText=True)
f.set_scientific(True)
f.set_powerlimits((0, 3))
ax.yaxis.set_major_formatter(f)
示例9: scale
def scale(args):
dataset_name = args.get('dataset')
scale = args.get('scale')
scale = [float(component) for component in scale.split(',')]
variable = args.get('variable')
if variable.endswith('_anom'):
variable = variable[0:-5]
anom = True
else:
anom = False
variable = variable.split(',')
with open_dataset(get_dataset_url(dataset_name)) as dataset:
variable_unit = get_variable_unit(dataset_name,
dataset.variables[variable[0]])
variable_name = get_variable_name(dataset_name,
dataset.variables[variable[0]])
if variable_unit.startswith("Kelvin"):
variable_unit = "Celsius"
if anom:
cmap = colormap.colormaps['anomaly']
variable_name = gettext("%s Anomaly") % variable_name
else:
cmap = colormap.find_colormap(variable_name)
if len(variable) == 2:
if not anom:
cmap = colormap.colormaps.get('speed')
variable_name = re.sub(
r"(?i)( x | y |zonal |meridional |northward |eastward )", " ",
variable_name)
variable_name = re.sub(r" +", " ", variable_name)
fig = plt.figure(figsize=(2, 5), dpi=75)
ax = fig.add_axes([0.05, 0.05, 0.25, 0.9])
norm = matplotlib.colors.Normalize(vmin=scale[0], vmax=scale[1])
formatter = ScalarFormatter()
formatter.set_powerlimits((-3, 4))
bar = ColorbarBase(ax, cmap=cmap, norm=norm, orientation='vertical',
format=formatter)
bar.set_label("%s (%s)" % (variable_name.title(),
utils.mathtext(variable_unit)))
buf = StringIO()
try:
plt.savefig(buf, format='png', dpi='figure', transparent=False,
bbox_inches='tight', pad_inches=0.05)
plt.close(fig)
return buf.getvalue()
finally:
buf.close()
示例10: plot_comparison_hydrographs
def plot_comparison_hydrographs(basin_name_to_out_indices_map, rea_config=None, gcm_config=None):
"""
:type basin_name_to_out_indices_map: dict
"""
assert isinstance(rea_config, RunConfig)
assert isinstance(gcm_config, RunConfig)
assert hasattr(rea_config, "data_daily")
assert hasattr(gcm_config, "data_daily")
bname_to_indices = OrderedDict([item for item in sorted(basin_name_to_out_indices_map.items(),
key=lambda item: item[1][1], reverse=True)])
print(bname_to_indices)
plot_utils.apply_plot_params(font_size=12, width_pt=None, width_cm=25, height_cm=12)
fig = plt.figure()
ncols = 3
nrows = len(bname_to_indices) // ncols + int(len(bname_to_indices) % ncols != 0)
gs = GridSpec(nrows, ncols)
ax_last = None
for pl_index, (bname, (i, j)) in enumerate(bname_to_indices.items()):
row = pl_index // ncols
col = pl_index % ncols
ax = fig.add_subplot(gs[row, col])
ax.plot(rea_config.data_daily[0], rea_config.data_daily[1][:, i, j], color="b", lw=2,
label=rea_config.label)
ax.plot(gcm_config.data_daily[0], gcm_config.data_daily[1][:, i, j], color="r", lw=2,
label=gcm_config.label)
ax.xaxis.set_major_locator(MonthLocator())
ax.xaxis.set_minor_locator(MonthLocator(bymonthday=15))
ax.xaxis.set_minor_formatter(FuncFormatter(lambda d, pos: num2date(d).strftime("%b")[0]))
plt.setp(ax.xaxis.get_majorticklabels(), visible=False)
ax.grid()
sfmt = ScalarFormatter(useMathText=True)
sfmt.set_powerlimits([-2, 2])
ax.yaxis.set_major_formatter(sfmt)
bbox_props = dict(boxstyle="round,pad=0.3", fc="cyan", ec="b", lw=1, alpha=0.5)
ax.annotate(bname, (0.9, 0.1), xycoords="axes fraction", bbox=bbox_props, zorder=10,
alpha=0.5, horizontalalignment="right", verticalalignment="bottom")
ax_last = ax
ax_last.legend(loc="upper right", bbox_to_anchor=(1, -0.2), borderaxespad=0, ncol=2)
img_file = img_folder.joinpath("bfe_hydrographs.eps")
with img_file.open("wb") as f:
fig.tight_layout()
fig.savefig(f, bbox_inches="tight", format="eps")
示例11: tick_formatter
def tick_formatter(powerlimits=None):
try:
from matplotlib.ticker import ScalarFormatter
except ImportError:
raise (MatplotlibUnavailableError("Matplotlib is required but unavailable on your system."))
except RuntimeError:
raise (MatplotlibDisplayError("Matplotlib unable to open display"))
if powerlimits is None:
powerlimits = (3, 3)
formatter = ScalarFormatter()
formatter.set_powerlimits(powerlimits)
return formatter
示例12: plotResults
def plotResults(a1, a2, b1, b2, fname, ofname):
#read data from csv file
print('Reading data from csv file...')
a = np.genfromtxt(fname, delimiter=';')
noRows = a.shape[0]
noCols = a.shape[1]
a = a[0:noRows, 0:(noCols-1)]
deltaX = a2-a1
deltaY = b2-b1
stepX = deltaX / (noRows)
stepY = deltaY / (noCols-1)
print('done.')
print('Preparing plot...')
fig = plt.figure(figsize=(5, 3), dpi=500)
ax = fig.gca(projection='3d')
X = np.arange(a1, a2, stepX)
Y = np.arange(b1, b2, stepY)
X, Y = np.meshgrid(X, Y)
Z = a
vMax=Z.max()
vMin=Z.min()
vMax=vMax+0.1*abs(vMax)
vMin=vMin-0.1*abs(vMin)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.Greys_r,
linewidth=0, antialiased=True, vmin=vMin, vmax=vMax)
zAxisFormatter = ScalarFormatter()
zAxisFormatter.set_scientific(True)
zAxisFormatter.set_powerlimits((0, 1))
#ax.zaxis.set_major_formatter(zAxisFormatter)
print('Drawing...')
fontSize=8 #set fontsize on plot
ax.set_xlabel('x', fontsize=fontSize)
ax.set_ylabel('y', fontsize=fontSize)
ax.zaxis.set_rotate_label(False)
ax.set_zlabel('u(x,y)', fontsize=fontSize, rotation=90)
ax.view_init(27, 35)
t = ax.zaxis.get_offset_text()
t.set_size(fontSize-2)
#t.set_position((0,0))
t.set_rotation(45)
t.set_verticalalignment('center')
#t.set_z(0)
plt.setp(ax.get_xticklabels(), fontsize=fontSize)
plt.setp(ax.get_yticklabels(), fontsize=fontSize)
plt.setp(ax.get_zticklabels(), fontsize=fontSize)
plt.legend()
cbar=fig.colorbar(surf, shrink=0.75, aspect=15)
cbar.ax.tick_params(labelsize=fontSize)
#plt.show()
plt.savefig(filename=ofname, format='eps')
plt.close()
示例13: show_slice_overlay
def show_slice_overlay(self, x_range, y_range, x, slice_y_data, y, slice_x_data):
"""sum along x and z within the box defined by qX- and qZrange.
sum along qx is plotted to the right of the data,
sum along qz is plotted below the data.
Transparent white rectangle is overlaid on data to show summing region"""
from matplotlib.ticker import FormatStrFormatter, ScalarFormatter
if self.fig == None:
print ("No figure for this dataset is available")
return
fig = self.fig
ax = fig.ax
extent = fig.im.get_extent()
if fig.slice_overlay == None:
fig.slice_overlay = ax.fill(
[x_range[0], x_range[1], x_range[1], x_range[0]],
[y_range[0], y_range[0], y_range[1], y_range[1]],
fc="white",
alpha=0.3,
)
fig.ax.set_ylim(extent[2], extent[3])
else:
fig.slice_overlay[0].xy = [
(x_range[0], y_range[0]),
(x_range[1], y_range[0]),
(x_range[1], y_range[1]),
(x_range[0], y_range[1]),
]
fig.sz.clear()
default_fmt = ScalarFormatter(useMathText=True)
default_fmt.set_powerlimits((-2, 4))
fig.sz.xaxis.set_major_formatter(default_fmt)
fig.sz.yaxis.set_major_formatter(default_fmt)
fig.sz.xaxis.set_major_formatter(FormatStrFormatter("%.2g"))
fig.sz.set_xlim(x[0], x[-1])
fig.sz.plot(x, slice_y_data)
fig.sx.clear()
fig.sx.yaxis.set_major_formatter(default_fmt)
fig.sx.xaxis.set_major_formatter(default_fmt)
fig.sx.yaxis.set_ticks_position("right")
fig.sx.yaxis.set_major_formatter(FormatStrFormatter("%.2g"))
fig.sx.set_ylim(y[0], y[-1])
fig.sx.plot(slice_x_data, y)
fig.im.set_extent(extent)
fig.canvas.draw()
示例14: __init__
def __init__(self, figure, x_label='', y_label=''):
"""
Initializes a _plot_list, which contains plot_data.
Keyword arguments:
figure -- The matplotlib figure to which the plots are added.
x_label -- The x-axis label to use for all plots (default: '')
y_label -- The y-axis label to use for all plots (default: '')
"""
self.x_label = x_label
self.y_label = y_label
self.figure = figure
self.sub_plots = []
# set default formatter for the time being
frmt = ScalarFormatter(useOffset = True)
frmt.set_powerlimits((-3,3))
frmt.set_scientific(True)
self.default_formatter = (frmt, frmt)
示例15: plot_learn_zips_summary
def plot_learn_zips_summary(name,control_zip,learn_zips,vals,skip_rows=0,png=False,num_mins=3):
_,control = read_zip(control_zip,skip_rows=skip_rows)
baseline = 1
scale = baseline/numpy.mean(control)
figsize = (5,2.5)
pylab.figure(figsize=figsize,dpi=300)
means = []
for learn_zip in learn_zips:
_,learn = read_zip(learn_zip,skip_rows=skip_rows)
means.append(numpy.mean(learn)*scale)
sorted_means = list(means)
sorted_means.sort()
min_means_loc = [vals[means.index(sorted_means[i])] for i in range(num_mins)]
ax = pylab.axes((0.18,0.2,0.8,0.7))
fmt = ScalarFormatter()
fmt.set_powerlimits((-3,4))
fmt.set_scientific(True)
ax.xaxis.set_major_formatter(fmt)
ax.xaxis.set_minor_locator(MultipleLocator(float(vals[1])-float(vals[0])))
pylab.plot(vals,means,color='k',linewidth=2)
pylab.plot(min_means_loc,sorted_means[:num_mins],'o',markerfacecolor='None')
pylab.plot(min_means_loc[0],sorted_means[0],'ko')
pylab.axhline(baseline,linestyle='--',linewidth=1,color='k')
pylab.ylabel('Mean relative error\n(learning vs. analytic)\n\n',ha='center')
pylab.xlabel(name)
pylab.axis('tight')
if png:
if not os.path.exists('png'):
os.mkdir('png')
pylab.savefig('png/'+learn_zips[0].split('-')[0]+'-summary.png',figsize=figsize,dpi=600)
else:
pylab.show()