Python matplotlib.ticker 模块,FixedLocator() 实例源码
我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用matplotlib.ticker.FixedLocator()。
def set_ticks(self, ticks, update_ticks=True):
"""
set tick locations. Tick locations are updated immediately unless
update_ticks is *False*. To manually update the ticks,call
*update_ticks* method explicitly.
"""
if cbook.iterable(ticks):
self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
else:
self.locator = ticks
if update_ticks:
self.update_ticks()
def set_ticklabels(self, ticklabels, update_ticks=True):
"""
set tick labels. Tick labels are updated immediately unless
update_ticks is *False*. To manually update the ticks,call
*update_ticks* method explicitly.
"""
if isinstance(self.locator, ticker.FixedLocator):
self.formatter = ticker.FixedFormatter(ticklabels)
if update_ticks:
self.update_ticks()
else:
warnings.warn("set_ticks() must have been called.")
def __init__(self, ax, mappable, **kw):
# Ensure the given mappable's norm has appropriate vmin and vmax set
# even if mappable.draw has not yet been called.
mappable.autoscale_None()
self.mappable = mappable
kw['cmap'] = cmap = mappable.cmap
kw['norm'] = norm = mappable.norm
if isinstance(mappable, contour.ContourSet):
CS = mappable
kw['alpha'] = mappable.get_alpha()
kw['boundaries'] = CS._levels
kw['values'] = CS.cvalues
kw['extend'] = CS.extend
#kw['ticks'] = CS._levels
kw.setdefault('ticks', ticker.FixedLocator(CS.levels, nbins=10))
kw['filled'] = CS.filled
ColorbarBase.__init__(self, **kw)
if not CS.filled:
self.add_lines(CS)
else:
if getattr(cmap, 'colorbar_extend', False) is not False:
kw.setdefault('extend', cmap.colorbar_extend)
if isinstance(mappable, martist.Artist):
kw['alpha'] = mappable.get_alpha()
ColorbarBase.__init__(self, **kw)
def set_ticks(self, nbins=len(ticks))
else:
self.locator = ticks
if update_ticks:
self.update_ticks()
def residuals_plot(ax, names, residuals, xl, yl, ylim=None, xticks=None,
xlabelpad=None, ylabelpad=None):
x = np.arange(len(names))
y = []
for name in names:
y.append(residuals[name][1])
# Set the axes ranges and axes labels
ax.set_xlabel(xl, labelpad=xlabelpad)
ax.set_ylabel(yl, labelpad=ylabelpad)
if ylim is None:
y_min = min(y)
ax.set_ylim(y_min - y_min * 0.15, 1)
else:
ax.set_ylim(ylim[0], ylim[1])
ax.set_xlim(-0.5, x[-1] + 0.5)
ax.xaxis.set_major_locator(FixedLocator(x))
ax.grid(False, which='major', axis='x')
bars = ax.bar(x, y, align='center', width=0.8, facecolor=PRIM+(0.5,), edgecolor=EC)
# labels = ['$\mathsf{%s: R}^2 = %.3f$' % (
# name.replace('-','\!\operatorname{-}\!'),r) for name,r in zip(names,y)]
labels = ['$\mathsf{R}^2 = %.3f$' %r for r in y]
autolabel(ax, bars, labels)
if xticks is None:
plt.setp(ax.get_xticklabels(), visible=False)
else:
ax.set_xticklabels(xticks, rotation='vertical')
def __init__(self, **kw):
# Ensure the given mappable's norm has appropriate vmin and vmax set
# even if mappable.draw has not yet been called.
mappable.autoscale_None()
self.mappable = mappable
kw['cmap'] = cmap = mappable.cmap
kw['norm'] = mappable.norm
if isinstance(mappable, nbins=10))
kw['filled'] = CS.filled
else:
if getattr(cmap, Artist):
kw['alpha'] = mappable.get_alpha()
ticks = kw.pop('ticks', None)
ticklabels = kw.pop('ticklabels', None)
self._base = ColorbarBase2(None, **kw)
if ticks:
self._base.set_ticks(ticks, update_ticks=False)
if ticks and ticklabels:
self._base.set_ticklabels(ticklabels, update_ticks=False)
def setLinesensor(self):
try:
self.compressLabel(self.sensorList)
x1=[]
x1pos=[]
labels1=[]
j = -1
x1pos.append(0)
labels1.append('')
# self.setTestData()
for i in self.sensorList:
if i.startX > j:
x1.append(i.startX)
j = i.startX
x1.append(i.stopX)
x1pos.append(i.labelPos)
labels1.append(i.label)
self.par1.xaxis.set_major_formatter(ticker.NullFormatter())
self.par1.xaxis.set_minor_locator(ticker.FixedLocator(x1pos))
self.par1.xaxis.set_minor_formatter(ticker.FixedFormatter(labels1))
self.par1.xaxis.set_ticks(x1)
except Exception as _err:
print(_err)
logging.exception(_err)
pass
def setLineRBW(self):
self.compressLabel(self.rbwList)
try:
x1 = []
x1pos = []
labels1 = []
j = -1
x1pos.append(0)
labels1.append('')
# self.setTestData()
for i in self.rbwList:
if i.startX > j:
x1.append(i.startX)
j = i.startX
x1.append(i.stopX)
x1pos.append(i.labelPos)
labels1.append(i.label)
# self.par2.spines["bottom"].set_position(("outward",50))
# self.par2.xaxis.set_ticks_position('bottom')
# self.par2.set_xscale('log')
self.par2.xaxis.set_major_formatter(ticker.NullFormatter())
self.par2.xaxis.set_minor_locator(ticker.FixedLocator(x1pos))
self.par2.xaxis.set_minor_formatter(ticker.FixedFormatter(labels1))
self.par2.xaxis.set_ticks(x1)
self.par2.xaxis.set_tick_params(which='minor',length=1,direction='out', pad=5, labelbottom='on')
self.par2.xaxis.set_tick_params(which='major',length=10,labelbottom='on')
except Exception as _err:
print(_err)
logging.exception(_err)
def set_longitude_grid(self, degrees):
"""
Set the number of degrees between each longitude grid.
"""
number = (360.0 / degrees) + 1
locs = np.linspace(-np.pi, np.pi, number, True)[1:]
locs[-1] -= 0.01 # Workaround for "back" gridlines showing.
self.xaxis.set_major_locator(FixedLocator(locs))
self._logitude_degrees = degrees
self.xaxis.set_major_formatter(self.ThetaFormatter(degrees))
def plot_loop(self, data, it):
"""
The actual function that updates the data in the plot initialized in :meth:`~.init`
:param data: The data that is recorded with :class:`~.PlotRecorder`. It can be a just a vector with one binary
value (0 or 1) for every spike source you want to plot (in which case the iteration number is used on the x axis)
OR a 2-D tuple with the first value containing the vector of spikes to plot as above and the second value
containing the corresponding x value.
:param it: The iteration number (independent of the actual x value)
:return:
"""
if not isinstance(data, tuple):
spikes = data
x = it
elif len(data) == 2 and isinstance(data, tuple):
spikes, x = data
else:
logger.error("Data is a tuple with too many values (should be at most 2): data: %s", data)
raise RuntimeError()
logger.debug("Plotting %s in %s", self.var_name, self.entity_name)
assert len(spikes.shape) == 1, "The spikes variable should be a vector,one for each source." \
"But its shape is {} at {}".format(spikes.shape, x)
assert np.logical_or(spikes == 0, spikes == 1).all(), "Spike data should be either or 1"
sps = spikes * (np.arange(len(spikes)) + 1)
sps[sps == 0.] = -10
self.spikes_list.append(sps)
self.xs.append(x)
if it == 0 and self.lines == []:
n_y = len(spikes)
for _ in range(n_y):
l, = self.ax.plot([], [], marker='.', linestyle='none', color='b', **self.plot_kwargs)
self.lines.append(l)
self.ax.set_ylim(1, len(spikes) + 1)
self.ax.yaxis.set_major_locator(FixedLocator([0, len(spikes) + 1]))
if it > 0 and it % self.plot_frequency == 0:
spike_list_arr = np.array(self.spikes_list)
for j, l in enumerate(self.lines):
l.set_data(self.xs, spike_list_arr[:, j])
self.ax.set_xlim(self.xs[-1] - 100, self.xs[-1])
self.ax.relim()
def _plot_sections(ax1, ax3, ax4, sections):
if sections is not None:
sec_labels = []
sec_locs = []
xgrid_locs = []
unique_sections = list(set(s['name'] for s in sections))
cmap = plt.get_cmap('gist_rainbow')
colors = [cmap(i) for i in np.linspace(0, 1, len(unique_sections))]
for sec in sections:
# get the time interval
tt = sec['time']
dur = tt[1] - tt[0]
xgrid_locs += tt # add the boundaries to grid locations
# get the plot limits
ylim = ax3.get_ylim()
# get the color code for the section
clr = colors[unique_sections.index(sec['name'])]
# create the rectangle
p = patches.Rectangle((tt[0], ylim[0]), dur, ylim[1],
alpha=0.3, facecolor=clr,
edgecolor='black')
ax4.add_patch(p)
sec_labels.append(sec['name'])
sec_locs.append(np.mean(tt))
# styling
ax4.set_xticks(sec_locs)
ax4.set_xticklabels(sec_labels, rotation=-15)
ax1.set_xticks(xgrid_locs, minor=True)
ax1.xaxis.grid(True, which='minor')
ax1.xaxis.set_major_locator(FixedLocator(
xgrid_locs, nbins=len(xgrid_locs) / 2 + 1))
plt.setp(ax4.get_yticklabels(), visible=False)
ax4.set_xlim(ax3.get_xlim())
else:
# no section labels
plt.setp(ax4.get_xticklabels(), visible=False)
def get_axis_properties(axis):
"""Return the property dictionary for a matplotlib.Axis instance"""
props = {}
label1On = axis._major_tick_kw.get('label1On', True)
if isinstance(axis, matplotlib.axis.XAxis):
if label1On:
props['position'] = "bottom"
else:
props['position'] = "top"
elif isinstance(axis, matplotlib.axis.YAxis):
if label1On:
props['position'] = "left"
else:
props['position'] = "right"
else:
raise ValueError("{0} should be an Axis instance".format(axis))
# Use tick values if appropriate
locator = axis.get_major_locator()
props['nticks'] = len(locator())
if isinstance(locator, ticker.FixedLocator):
props['tickvalues'] = list(locator())
else:
props['tickvalues'] = None
# Find tick formats
formatter = axis.get_major_formatter()
if isinstance(formatter, ticker.NullFormatter):
props['tickformat'] = ""
elif not any(label.get_visible() for label in axis.get_ticklabels()):
props['tickformat'] = ""
else:
props['tickformat'] = None
# Get axis scale
props['scale'] = axis.get_scale()
# Get major tick label size (assumes that's all we really care about!)
labels = axis.get_ticklabels()
if labels:
props['fontsize'] = labels[0].get_fontsize()
else:
props['fontsize'] = None
# Get associated grid
props['grid'] = get_grid_style(axis)
return props
def _ticker(self):
'''
Return two sequences: ticks (colorbar data locations)
and ticklabels (strings).
'''
locator = self.locator
formatter = self.formatter
if locator is None:
if self.boundaries is None:
if isinstance(self.norm, colors.Nonorm):
nv = len(self._values)
base = 1 + int(nv / 10)
locator = ticker.IndexLocator(base=base, offset=0)
elif isinstance(self.norm, colors.Boundarynorm):
b = self.norm.boundaries
locator = ticker.FixedLocator(b, nbins=10)
elif isinstance(self.norm, colors.Lognorm):
locator = ticker.LogLocator()
else:
locator = ticker.MaxNLocator()
else:
b = self._boundaries[self._inside]
locator = ticker.FixedLocator(b, nbins=10)
if isinstance(self.norm, colors.Nonorm):
intv = self._values[0], self._values[-1]
else:
intv = self.vmin, self.vmax
locator.create_dummy_axis(minpos=intv[0])
formatter.create_dummy_axis(minpos=intv[0])
locator.set_view_interval(*intv)
locator.set_data_interval(*intv)
formatter.set_view_interval(*intv)
formatter.set_data_interval(*intv)
b = np.array(locator())
ticks = self._locate(b)
inrange = (ticks > -0.001) & (ticks < 1.001)
ticks = ticks[inrange]
b = b[inrange]
formatter.set_locs(b)
ticklabels = [formatter(t, i) for i, t in enumerate(b)]
offset_string = formatter.get_offset()
return ticks, offset_string
def _ticker(self):
'''
Return the sequence of ticks (colorbar data locations),
ticklabels (strings),and the corresponding offset string.
'''
locator = self.locator
formatter = self.formatter
if locator is None:
if self.boundaries is None:
if isinstance(self.norm, offset_string
def setLineAMP(self):
self.compressLabel(self.ampList)
try:
x1 = []
x1pos = []
labels1 = []
j = -1
x1pos.append(0)
labels1.append('')
# self.setTestData()
for i in self.ampList:
if i.startX > j:
x1.append(i.startX)
j = i.startX
x1.append(i.stopX)
x1pos.append(i.labelPos)
labels1.append(i.label)
if not self.line2TextFlag:
# self.par3.text(-0.05,-0.33,"amp",horizontalalignment='left',transform=self.host.transAxes)
# self.par3.text(-0.05,-0.40,"att",transform=self.host.transAxes)
# self.par3.spines["bottom"].set_position(("outward",90))
self.par3.xaxis.set_ticks_position('bottom')
self.par3.xaxis.set_major_formatter(ticker.NullFormatter())
self.par3.xaxis.set_minor_formatter(ticker.NullFormatter())
self.par3.xaxis.set_tick_params(which='minor',direction='in', pad=-10, labelbottom='on')
self.par3.xaxis.set_tick_params(which='major', pad=-20,labelbottom='on')
self.line2TextFlag = True
self.par3.xaxis.set_minor_locator(ticker.FixedLocator(x1pos))
self.par3.xaxis.set_minor_formatter(ticker.FixedFormatter(labels1))
self.par3.xaxis.set_ticks(x1)
#set color for autorange indication
_Ret = self.par3.xaxis.get_minorticklabels()
n = 0
for i in _Ret:
if self.ampList[n].color =='r':
i._color = 'r' #sorry,found no other access
if n < len(self.ampList) - 1:
n += 1
except Exception as _err:
print(_err)
logging.exception(_err)
pass
def setLineATT(self):
self.compressLabel(self.attList)
try:
x1 = []
x1pos = []
labels1 = []
j = -1
x1pos.append(0)
labels1.append('')
# self.setTestData()
for i in self.attList:
if i.startX > j:
x1.append(i.startX)
j = i.startX
x1.append(i.stopX)
x1pos.append(i.labelPos)
labels1.append(i.label)
# self.par4.spines["bottom"].set_position(("outward",90))
# self.par4.xaxis.set_ticks_position('bottom')
# # self.par1.set_xlim(1e3,1e9)
# self.par4.set_xscale('log')
self.par4.xaxis.set_major_formatter(ticker.NullFormatter())
self.par4.xaxis.set_minor_locator(ticker.FixedLocator(x1pos))
self.par4.xaxis.set_minor_formatter(ticker.FixedFormatter(labels1))
self.par4.xaxis.set_ticks(x1)
self.par4.xaxis.set_tick_params(which='minor', labelbottom='on')
self.par4.xaxis.set_tick_params(which='major',labelbottom='on')
_Ret = self.par4.xaxis.get_minorticklabels()
n = 0
for i in _Ret:
if self.attList[n].color =='r':
i._color = 'red'
if n < len(self.attList) - 1:
n += 1
# self.signalGraphUpdate.emit()
except Exception as _err:
print(_err)
logging.exception(_err)
pass
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。