Python matplotlib.ticker 模块,ScalarFormatter() 实例源码
我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用matplotlib.ticker.ScalarFormatter()。
def __call__(self, x, pos=None):
# call the original ScalarFormatter
rv = ticker.ScalarFormatter.__call__(self, pos)
# check if we really use TeX
if plt.rcParams["text.usetex"]:
# if we have the string ^{- there is a negative exponent
# where the minus sign is replaced by the short hyphen
rv = re.sub(r'-', r'\mhyphen', rv)
if rv.endswith('.0'):
rv = rv.replace('.0', '')
return rv
### for the A&A article class
def draw_histogram(latencies_ms,
bins,
cutoff_time_ms,
draw_xlabel=True,
draw_ylabel=True):
"""
Draw one individual histogram.
"""
n, bins, patches = plt.hist(latencies_ms, color='white', hatch='/')
if draw_xlabel:
plt.xlabel("Packet latency (ms)")
if draw_ylabel:
plt.ylabel("Frequency")
plt.gca().set_xscale("log")
plt.gca().xaxis.set_major_formatter(ScalarFormatter())
plt.xlim([min(bins), max(bins)])
plt.xticks([1, cutoff_time_ms, 100])
def prepare_spectrogram_plot(self, type: SpectrogramType = SpectrogramType.power_level,
frequency_scale: SpectrogramFrequencyScale = SpectrogramFrequencyScale.linear) -> None:
spectrogram = self.example.spectrogram(type, frequency_scale=frequency_scale)
figure, axes = plt.subplots(1, 1)
use_mel = frequency_scale == SpectrogramFrequencyScale.mel
plt.title("\n".join(wrap(
"{0}{1} spectrogram for {2}".format(("mel " if use_mel else ""), type.value, str(self)), width=100)))
plt.xlabel("time (data every {}ms)".format(round(1000 / self.example.time_step_rate())))
plt.ylabel("frequency (data evenly distributed on {} scale,{} total)".format(
frequency_scale.value, self.example.frequency_count_from_spectrogram(spectrogram)))
mel_frequencies = self.example.mel_frequencies()
plt.imshow(
spectrogram, cmap='gist_heat', origin='lower', aspect='auto', extent=
[0, self.example.duration_in_s,
librosa.hz_to_mel(mel_frequencies[0])[0] if use_mel else 0,
librosa.hz_to_mel(mel_frequencies[-1])[0] if use_mel else self.example.highest_detectable_frequency()])
plt.colorbar(label="{} ({})".format(
type.value,
"in{} dB,not aligned to a particular base level".format(" something similar to" if use_mel else "") if
type == SpectrogramType.power_level else "only proportional to physical scale"))
class ScalarFormatterWithUnit(ScalarFormatter):
def __init__(self, unit: str):
super().__init__()
self.unit = unit
def __call__(self, pos=None) -> str:
return super().__call__(x, pos) + self.unit
axes.xaxis.set_major_formatter(ScalarFormatterWithUnit("s"))
axes.yaxis.set_major_formatter(
FuncFormatter(lambda value, pos: "{}mel = {}Hz".format(int(value), int(
librosa.mel_to_hz(value)[0]))) if use_mel else ScalarFormatterWithUnit("Hz"))
figure.set_size_inches(19.20, 10.80)
def _plot(cls, report, axes, categories, styles):
# display grid
axes.grid(b=True, linestyle='-', color='0.75')
has_points = False
# Generate the scatter plots
for category, coords in sorted(categories.items()):
X, Y = zip(*coords)
axes.scatter(X, Y, s=42, label=category, **styles[category])
if X and Y:
has_points = True
if report.xscale == 'linear' or report.yscale == 'linear':
plot_size = report.missing_val * 1.01
else:
plot_size = report.missing_val * 1.25
# make 5 ticks above and below 1
yticks = []
tick_step = report.ylim_top**(1/5.0)
for i in xrange(-5, 6):
yticks.append(tick_step**i)
axes.set_yticks(yticks)
axes.get_yaxis().set_major_formatter(ticker.ScalarFormatter())
axes.set_xlim(report.xlim_left or -1, report.xlim_right or plot_size)
axes.set_ylim(report.ylim_bottom or -1, report.ylim_top or plot_size)
for axis in [axes.xaxis, axes.yaxis]:
MatplotlibPlot.change_axis_formatter(axis,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls, axes.yaxis]:
MatplotlibPlot.change_axis_formatter(
axis,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def _plot(cls,
report.missing_val if report.show_missing else None)
return has_points
def plot_formatter(self):
ax=self.axs[0]
#
if ax.get_xlim()[1]-ax.get_xlim()[0] > 3600./86400.:
minloc = mpl.dates.HourLocator()
xformat = mpl.dates.DateFormatter('%H:%M')
else:
minloc = mpl.dates.MinuteLocator()
xformat = mpl.dates.DateFormatter('%H:%M')
#for ax in self.subplt:
x_range=ax.get_xlim()[1]-ax.get_xlim()[0]
_xlim=(ax.get_xlim()[0]-(x_range/100.)*3,
ax.get_xlim()[1]+(x_range/100.)*3)
ax.set_xlim(_xlim)
for ax in self.axs:
ax.grid(b='on')
#Todo
try:
plt.setp(ax.get_xticklabels(), visible=False)
except:
pass
ax.xaxis.set_major_formatter(xformat)
ax.xaxis.set_major_locator(minloc)
if ax.get_xticklabels().__len__() > 6:
ax.xaxis.set_major_locator(MaxNLocator(6))
ax.yaxis.set_major_formatter(ScalarFormatter(uSEOffset=False))
#http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot
#Box = ax.get_position()
#ax.set_position([Box.x0,Box.y0,Box.width * 0.90,Box.height])
#ax.legend(loc='center left',bBox_to_anchor=(1,0.5))
#ax.legend()
leg=ax.legend()
leg.get_frame().set_alpha(0.5)
plt.setp(ax.get_xticklabels(), visible=True)
ax.set_xlabel('utc')
def plot_formatter(self):
#for ax in self.subplt:
ax=self.axs[0]
y_range=ax.get_ylim()[1]-ax.get_ylim()[0]
_ylim=(ax.get_ylim()[0]-(y_range/100.)*3,
ax.get_ylim()[1]+(y_range/100.)*3)
ax.set_ylim(_ylim)
for ax in self.axs:
ax.grid(b='on')
plt.setp(ax.get_yticklabels(), visible=False)
#http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot
#Box = ax.get_position()
#ax.set_position([Box.x0,Box.y0 + Box.height * 0.2,Box.width,Box.height * 0.8])
#ax.set_position([Box.x0,Box.height * 0.8])
#ax.legend(loc='upper center',bBox_to_anchor=(0.5,-0.12))
leg=ax.legend()
leg.get_frame().set_alpha(0.5)
if ax.get_xticklabels().__len__() > 5:
ax.xaxis.set_major_locator(MaxNLocator(5))
ax.yaxis.set_major_formatter(ScalarFormatter(uSEOffset=False))
#set y-axis lower limit to zero
cur_ylim = ax.get_ylim()
if cur_ylim[0] < 0:
ax.set_ylim((0, cur_ylim[1]))
plt.setp((self.axs[0].get_yticklabels()), visible=True)
(self.axs[0]).set_ylabel('alt (m)')
def cct_duv_diagram(samples=100, fig=None, ax=None):
''' Creates a CCT-Duv diagram,for more @R_125_4045@ion see Calculation of
CCT and Duv and Practical Conversion Formulae,Yoshi Ohno,2011.
Args:
samples (`int`): number of samples on the background.
fig (`matplotlib.figure.figure`): figure to plot in.
ax (`matplotlib.axes.Axis`): axis to plot in.
Returns:
`tuple` containing:
`matplotlib.figure.figure`: figure containing the plot.
`matplotlib.axes.Axis`: Axis containing the plot.
'''
raise UserWarning('this type of plot is not yet properly implemented')
xlim = (2000, 10000)
ylim = (-0.03, 0.03)
cct = np.linspace(xlim[0], xlim[1], samples) # todo: even sampling along log,not linear
duv = np.linspace(ylim[0], ylim[1], samples)
upvp = np.empty((samples, samples, 2))
for i, cct_v in enumerate(cct):
for j, duv_v in enumerate(duv):
upvp[i, j, :] = CCT_Duv_to_uvprime(cct_v, duv_v)
xy = uvprime_to_xy(upvp)
xyz = xy_to_XYZ(xy)
dat = XYZ_to_sRGB(xyz)
maximum = np.max(dat, axis=-1)
dat /= maximum[..., np.newaxis]
dat = np.clip(dat, 0, 1)
fig, ax = share_fig_ax(fig, ax)
ax.imshow(dat,
extent=[*xlim, *ylim],
interpolation='bilinear',
origin='lower',
aspect='auto')
tick = ticker.ScalarFormatter()
tick.set_powerlimits((-3, 20))
ax.xaxis.set_major_formatter(tick)
ax.set(xlim=xlim, xlabel='CCT', xscale='log',
ylim=ylim, ylabel='Duv')
return fig, ax
def __init__(self, data, cbname, cblinthresh, cmap, extent, zlim,
figure_size, fontsize, aspect, figure, cax):
from matplotlib.ticker import ScalarFormatter
self._draw_colorbar = True
self._draw_axes = True
self._fontsize = fontsize
self._figure_size = figure_size
# Compute layout
fontscale = float(fontsize) / 18.0
if fontscale < 1.0:
fontscale = np.sqrt(fontscale)
if iterable(figure_size):
fsize = figure_size[0]
else:
fsize = figure_size
self._cb_size = 0.0375*fsize
self._ax_text_size = [1.2*fontscale, 0.9*fontscale]
self._top_buff_size = 0.30*fontscale
self._aspect = ((extent[1] - extent[0])/(extent[3] - extent[2])).in_cgs()
self._unit_aspect = aspect
size, axrect, caxrect = self._get_best_layout()
super(WindowPlotMPL, self).__init__(
size, caxrect, cax)
self._init_image(data, aspect)
# In matplotlib 2.1 and newer we'll be able to do this using
# self.image.axes.ticklabel_format
# See https://github.com/matplotlib/matplotlib/pull/6337
formatter = ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-2, 3))
self.image.axes.xaxis.set_major_formatter(formatter)
self.image.axes.yaxis.set_major_formatter(formatter)
if cbname == 'linear':
self.cb.formatter.set_scientific(True)
self.cb.formatter.set_powerlimits((-2, 3))
self.cb.update_ticks()
def heatmap(X, Z, ax=None, logy=True, cbar=True, hide_low=True,
cmap=default_cmap, fig_kws={}, cbar_kws={}, plot_kws={}, **kwargs):
"""Plot the heatmap of the particle size distribution.
"""
# Set the colorbar min and max based on the min and max of the values
cbar_min = kwargs.pop('cbar_min', Z.min() if Z.min() > 0.0 else 1.)
cbar_max = kwargs.pop('cbar_max', Z.max())
# copy to avoid modifying original data
Z_plot = Z.copy()
if hide_low:
# Hide NaN values
Z_plot = nan_to_num(Z_plot)
# Increase values below cbar_min to cbar_min
below_min = Z_plot < cbar_min
Z_plot[below_min] = cbar_min
# Set the plot_kws
plot_kws = dict(dict(norm=Lognorm(vmin=cbar_min, vmax=cbar_max), cmap=cmap),
**plot_kws)
# Set the figure keywords
fig_kws = dict(dict(figsize=(16,8)), **fig_kws)
if ax is None:
plt.figure(**fig_kws)
ax = plt.gca()
# Plot the data as a pcolormesh
im = ax.pcolormesh(X, Z_plot, **plot_kws)
# Set the ylim to match the data
ax.set_ylim([Y.min(), Y.max()])
# Set the axis to be log in the y-axis
if logy:
ax.semilogy()
ax.yaxis.set_major_formatter(ScalarFormatter())
ax.set_ylabel("$D_p \; [nm]$")
if cbar:
# Set the figure keywords
cbar_kws = dict(dict(label='$dN/dlogD_p \; [cm^{-3}]$'), **cbar_kws)
clb = plt.colorbar(im, **cbar_kws)
return ax
def SED_plotting_settings(x, ydata):
"""
This function produces the setting for the figures for SED plotting.
**Input:
- all nus,and data (to make the plot limits depending on the data)
"""
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()
#-- Latex -------------------------------------------------
rc('text', usetex=True)
rc('font', family='serif')
rc('axes', linewidth=1.5)
#-------------------------------------------------------------
# ax1.set_title(r"\textbf{SED of Type 2}" + r"\textbf{ AGN }"+ "Source Nr. "+ source + "\n . \n . \n .",fontsize=17,color='k')
ax1.set_xlabel(r'rest-frame $\mathbf{log \ \nu} [\mathtt{Hz}] $', fontsize=13)
ax2.set_xlabel(r'$\mathbf{\lambda} [\mathtt{\mu m}] $', fontsize=13)
ax1.set_ylabel(r'$\mathbf{\nu L(\nu) [\mathtt{erg \ } \mathtt{ s}^{-1}]}$',fontsize=13)
ax1.tick_params(axis='both',reset=False,which='major',length=8,width=1.5)
ax1.tick_params(axis='both',which='minor',length=4,width=1.5)
ax1.set_autoscalex_on(True)
ax1.set_autoscaley_on(True)
ax1.set_xscale('linear')
ax1.set_yscale('log')
mediandata = np.median(ydata)
ax1.set_ylim(mediandata /50.,mediandata * 50.)
ax2.set_xscale('log')
ax2.set_yscale('log')
ax2.set_ylim( mediandata /50., mediandata * 50.)
ax2.get_xaxis().set_major_formatter(ticker.ScalarFormatter())
ax2.tick_params(axis='both',width=1.5)
ax2.tick_params(axis='both',width=1.5)
x2 = (2.98e14/ x)[::-1] # Wavelenght axis
ax2.plot(x2, np.ones(len(x2)), alpha=0)
ax2.invert_xaxis()
ax2.set_xticks([100., 10.,1., 0.1])
return fig, ax1, ax2
def _make_ms1(fig, mz, xy, scan_mode, pm_scanDot, title=None, half_window=4.2):
'''Plots an MS scan,centered on the target mz.
This is an internal method,it expects a matplotlib figure instance'''
fig.clear()
fig.set_facecolor('w')
if scan_mode == 'c':
plot_xy = []
for sc in xy:
# add data point with zeros before and after. the x stays the same,
# which means the lines are all vertical (looks nicer)
plot_xy.extend(((sc[0],0), sc, (sc[0],0)))
else:
plot_xy = xy
axes = fig.add_axes([0.125, 0.1, 0.775, 0.8])
axes.plot([i[0] for i in plot_xy],
[i[1] for i in plot_xy],
c='k')
if pm_scanDot:
axes.set_xlim((pm_scanDot[0] - half_window, pm_scanDot[0] + half_window))
try:
axes.set_ylim((0.0, max(i[1] for i in xy if abs(i[0] - pm_scanDot[0]) <= half_window) * 1.1))
except ValueError:
axes.set_ylim((0.0, 1.0))
axes.axvline(x=pm_scanDot[0], ymin=0, ymax=1, ls='--', c='b')
if title is None:
if isinstance(mz, float):
mz = '%.3f' % mz
title = '%s m/z' % mz
if title:
axes.set_title(title)
axes.set_xlabel('m/z')
axes.set_ylabel('Relative Abundance')
axes.xaxis.set_major_formatter(ScalarFormatter(uSEOffset=False, useMathText=True))
return (xy,)
def _make_xic(fig, xic_time, xic_int, scan_dot, bin_times, bin_ints, title=None):
'''Plots a XIC,with labels for the primary MSMS scan and any neighboring scans
in the same time and mz area.
This is an internal method,it expects a matplotlib figure instance'''
#assert len(scan_dot) == 2
if len(scan_dot) != 2 and scan_dot != None:
if len(scan_dot) >= 1 and len(scan_dot[0]) == 2:
scan_dot = scan_dot[0]
else:
scan_dot = None
fig.clear()
fig.set_facecolor('w')
axes = fig.add_axes([0.125, 0.8])
axes.plot(xic_time, '--rs', linewidth=2, markeredgecolor='k',
markerfacecolor='g', markersize=5)
if len(bin_times) > 0:
axes.plot(bin_times, 'yo', markersize=10)
# plot the scan dot last,so it stays on top of other markers
if scan_dot is not None:
axes.plot([scan_dot[0]], [scan_dot[1]], 'b^', markersize=10)
if title is None:
if isinstance(mz, float):
mz = '%.3f' % mz
title = '%s m/z' % mz
if title:
axes.set_title(title)
axes.set_xlabel('Time (min)')
axes.set_ylabel('Abundance')
axes.xaxis.set_major_formatter(ScalarFormatter(uSEOffset=False, useMathText=True))
return (zip(xic_time, xic_int) + ([scan_dot] if scan_dot else []),)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。