本文整理汇总了Python中matplotlib.ticker.FuncFormatter方法的典型用法代码示例。如果您正苦于以下问题:Python ticker.FuncFormatter方法的具体用法?Python ticker.FuncFormatter怎么用?Python ticker.FuncFormatter使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.ticker
的用法示例。
在下文中一共展示了ticker.FuncFormatter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_index
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def plot_index(self, methods='mv'):
block_index=self.block_index('close')
def format_date(x, pos=None):
# 保证下标不越界,很重要,越界会导致最终plot坐标轴label无显示
thisind = np.clip(int(x+0.5), 0, N-1)
# print(thisind)
return block_index.index[thisind].strftime('%Y-%m-%d %H:%M')
fig = plt.figure(figsize=(14, 12))
ax = fig.add_subplot(1, 1, 1)
plt.style.use('ggplot')
plt.title('QUANTAXIS BLOCK ANA {}'.format(
self.name), fontproperties="SimHei")
N = len(block_index)
block_index.reset_index()[0].plot()
self.block_index('lv').reset_index()[0].plot()
self.block_index('close').reset_index()[0].plot()
self.block_index('volume').reset_index()[0].plot()
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
plt.legend(['market_value', 'liquidity_value', 'close', 'volume'])
plt.show()
示例2: axisinfo
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def axisinfo(unit, axis):
'return AxisInfo instance for x and unit'
if unit == radians:
return units.AxisInfo(
majloc=ticker.MultipleLocator(base=np.pi/2),
majfmt=ticker.FuncFormatter(rad_fn),
label=unit.fullname,
)
elif unit == degrees:
return units.AxisInfo(
majloc=ticker.AutoLocator(),
majfmt=ticker.FormatStrFormatter(r'$%i^\circ$'),
label=unit.fullname,
)
elif unit is not None:
if hasattr(unit, 'fullname'):
return units.AxisInfo(label=unit.fullname)
elif hasattr(unit, 'unit'):
return units.AxisInfo(label=unit.unit.fullname)
return None
示例3: plot
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def plot(self, df, database_name, test_name, y_label):
means = df.rolling(max(df.index.max() // 20, 1)).mean()
ax = means.plot(
title=test_name, alpha=0.8,
xlim=(0, means.index.max() * 1.05),
ylim=(0, means.max().max() * 1.05),
)
ax.set(xlabel='Amount of objects in table', ylabel=y_label)
ax.xaxis.set_major_formatter(
FuncFormatter(lambda v, pos: prefix_unit(v, '', -3)))
if y_label in self.ticks_formatters:
ax.yaxis.set_major_formatter(self.ticks_formatters[y_label])
legend = ax.legend(
loc='upper center', bbox_to_anchor=(0.5, 0.0),
bbox_transform=plt.gcf().transFigure,
fancybox=True, shadow=True, ncol=3)
filename = ('%s - %s.svg' % (database_name,
test_name)).replace(' ', '_')
plt.savefig(
os.path.join(self.results_path, filename),
bbox_extra_artists=(legend,), bbox_inches='tight',
)
示例4: create_example_s_curve_plot
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def create_example_s_curve_plot(self):
# Initialize plot
fig, ax = plt.subplots(figsize=(8, 4))
# Plot example S-response curve
x = np.arange(0, 20100, 100)
y = self.logistic_function(x, L=10000, k=0.0007, x_0=10000)
ax.plot(x, y, '-', label="Radio")
# Set plot options and show plot
ax.legend(loc='right')
plt.xlim([0, 20000])
plt.xlabel('Radio spend in euros')
plt.ylabel('Additional sales')
plt.title('Example of S-shaped response curve')
plt.tight_layout()
plt.grid()
ax.get_xaxis().set_major_formatter(tkr.FuncFormatter(lambda x, p: format(int(x), ',')))
ax.get_yaxis().set_major_formatter(tkr.FuncFormatter(lambda x, p: format(int(x), ',')))
plt.show()
示例5: wrap_formatter
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def wrap_formatter(formatter):
"""
Wraps formatting function or string in
appropriate matplotlib formatter type.
"""
if isinstance(formatter, ticker.Formatter):
return formatter
elif callable(formatter):
args = [arg for arg in _getargspec(formatter).args
if arg != 'self']
wrapped = formatter
if len(args) == 1:
def wrapped(val, pos=None):
return formatter(val)
return ticker.FuncFormatter(wrapped)
elif isinstance(formatter, basestring):
if re.findall(r"\{(\w+)\}", formatter):
return ticker.StrMethodFormatter(formatter)
else:
return ticker.FormatStrFormatter(formatter)
示例6: _plot_yearly_returns
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def _plot_yearly_returns(self, stats, ax=None, **kwargs):
"""
Plots a barplot of returns by year.
"""
def format_perc(x, pos):
return '%.0f%%' % x
returns = stats['returns']
if ax is None:
ax = plt.gca()
y_axis_formatter = FuncFormatter(format_perc)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))
ax.yaxis.grid(linestyle=':')
yly_ret = perf.aggregate_returns(returns, 'yearly') * 100.0
yly_ret.plot(ax=ax, kind="bar")
ax.set_title('Yearly Returns (%)', fontweight='bold')
ax.set_ylabel('')
ax.set_xlabel('')
ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
ax.xaxis.grid(False)
return ax
示例7: read_data_for_battery_plot
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def read_data_for_battery_plot(self):
bd = BatteryDriver()
data = bd.get_history_charge()
x = []
y = []
for element in data:
x.append(element[0])
y.append(element[1])
self.ax.cla()
self.ax.set_xlim(min(x), max(x))
self.ax.set_ylim(-10, 110)
self.ax.grid(True)
def format_date(x, pos=None):
ltime = time.localtime(x)
return time.strftime('%H:%M', ltime)
self.ax.xaxis.set_major_formatter(
ticker.FuncFormatter(format_date))
self.fig.autofmt_xdate()
self.ax.plot(x, y)
self.fig.canvas.draw()
return True
示例8: add_plot
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def add_plot(self, plot):
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*self.settings.x_scaling))
self.axes.xaxis.set_major_formatter(ticks)
if plot.minimum is None and plot.maximum is None:
range = [min(plot.timing_data.data), max(plot.timing_data.data)]
elif plot.range_type == "absolute":
range = [plot.minimum, plot.maximum]
print(range)
if len(numpy.intersect1d(range, plot.timing_data.data)) == 0:
msg = QtGui.QMessageBox()
msg.setIcon(QtGui.QMessageBox.Warning)
msg.setText("The specified range is invalid for data set as they do not overlap. Falling back to plotting the full range instead:\n [min(data), max(data)].")
msg.exec()
logging.warning("Specified range is invalid for data. Falling back to [min(data), max(data)].")
plot.minimum = min(plot.timing_data.data)
plot.maximum = max(plot.timing_data.data)
range = [plot.minimum, plot.maximum]
else:
range = [plot.timing_data.quantile(plot.minimum), plot.timing_data.quantile(plot.maximum)]
self.add_plot_raw(plot.timing_data.data, plot.bins, plot.style, range, plot.label, plot.color)
示例9: plot_series
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def plot_series(self, from_time, to_time, channels='all', ax=None):
"""Plot observations in a selected number of channels
"""
if channels == 'all':
channels = range(self.n_channels)
ax = ax if ax else plt
f, axs = plt.subplots(len(channels), 1)
formatter = FuncFormatter(lambda x, pos: from_time + int(x))
for ax, ch in zip(axs, channels):
ax.plot(self.reader[from_time:to_time, ch])
ax.set_title('Channel {}'.format(ch), fontsize=25)
ax.xaxis.set_major_formatter(formatter)
ax.tick_params(axis='x', which='major', labelsize=25)
plt.tight_layout()
示例10: set_formatter
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def set_formatter(ax, is_int=True, which="xy"):
"""Formats axis values.
Input
- ax: which ax object to format
- which: axis
Output
- formatted ax object
"""
formatter = ticker.FuncFormatter(lambda x, p: format(int(x), ","))
if "x" in which:
ax.get_xaxis().set_major_formatter(formatter)
if "y" in which:
ax.get_yaxis().set_major_formatter(formatter)
示例11: util_plot2d
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def util_plot2d(metric, title='', subtitle = '', line_size=2, title_size=17,date_formatter='%b-%d-%y %H-%M',plot_size=(6,6)):
if not isinstance(metric, list):
sys.exit("metric should have class 'list'")
if not isinstance(title, str):
sys.exit("title should have class 'str'")
if not isinstance(subtitle, str):
sys.exit("subtitle should have class 'str'")
times=util_timezone(metric[0])
def format_date(x, pos=None):
thisind = np.clip(int(x+0.5), 0, N-1)
return times[thisind].strftime(date_formatter)
N = len(metric[1])
ind = np.arange(N) # the evenly spaced plot indices
fig, ax = plt.subplots()
ax.plot(ind, metric[1], lw=line_size)
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()
plt.suptitle(title, y=0.99, fontsize=title_size)
plt.title(subtitle, fontsize=title_size-5)
plt.rcParams['figure.figsize'] = plot_size
plt.grid(True)
plt.show()
示例12: _plotStats
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def _plotStats(self, df, strategyName):
"""
绘制账户盈亏统计图
"""
def _dateFormatter(x, pos):
if not (0 <= int(x) < df.shape[0]):
return None
return df.index[int(x)].strftime("%y-%m-%d")
# create grid spec
gs = GridSpec(4, 1)
gs.update(hspace=0)
# subplot for PnL
axPnl = plt.subplot(gs[:-1, :])
axPnl.grid(True)
axPnl.set_title('{}: 盈亏(%)'.format(strategyName))
# set x ticks
x = [x for x in range(df.shape[0])]
xspace = max((len(x)+9)//10, 1)
axPnl.xaxis.set_major_locator(FixedLocator(x[:-xspace-1: xspace] + x[-1:]))
axPnl.xaxis.set_major_formatter(FuncFormatter(_dateFormatter))
# plot pnl
for name in df.columns:
if name not in ['持仓资金(%)', '持仓股票数']:
axPnl.plot(x, df[name].values, label=name)
axPnl.legend(loc='upper left', frameon=False)
# subplot for position
axPos = plt.subplot(gs[-1, :], sharex=axPnl)
axPos.grid(True)
axPos.bar(x, df['持仓资金(%)'].values, label='持仓资金(%)')
axPos.plot(x, df['持仓资金(%)'].values.cumsum()/np.array(list(range(1, df.shape[0] + 1))), label='平均持仓资金(%)', color='g')
axPos.plot(x, df['持仓股票数'].values, label='持仓股票数', color='r')
axPos.legend(loc='upper left', frameon=False)
示例13: draw_matrix_user_ranking
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def draw_matrix_user_ranking(df_stat, higher_better=False, fig=None, cmap='tab20'):
""" show matrix as image, sorted per column and unique colour per user
:param DF df_stat: table where index are users and columns are scoring
:param bool higher_better: ranking such that larger value is better
:param fig: optional figure
:param str cmap: color map
:return Figure:
>>> import pandas as pd
>>> df = pd.DataFrame(np.random.random((5, 3)), columns=list('abc'))
>>> draw_matrix_user_ranking(df) # doctest: +ELLIPSIS
<...>
"""
ranking = compute_matrix_user_ranking(df_stat, higher_better)
if fig is None:
fig, _ = plt.subplots(figsize=np.array(df_stat.values.shape[::-1]) * 0.35)
ax = fig.gca()
arange = np.linspace(-0.5, len(df_stat) - 0.5, len(df_stat) + 1)
norm = plt_colors.BoundaryNorm(arange, len(df_stat))
fmt = plt_ticker.FuncFormatter(lambda x, pos: df_stat.index[x])
draw_heatmap(ranking, np.arange(1, len(df_stat) + 1), df_stat.columns, ax=ax,
cmap=plt.get_cmap(cmap, len(df_stat)), norm=norm,
cbar_kw=dict(ticks=range(len(df_stat)), format=fmt),
cbar_label='Methods')
ax.set_ylabel('Ranking')
fig.tight_layout()
return fig
示例14: pimp_axis
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def pimp_axis(x_or_y_ax):
"""Remove trailing zeros.
"""
x_or_y_ax.set_major_formatter(ticker.FuncFormatter(ticks_formatter))
示例15: test_bbox_inches_tight_suptile_legend
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import FuncFormatter [as 别名]
def test_bbox_inches_tight_suptile_legend():
plt.plot(list(xrange(10)), label='a straight line')
plt.legend(bbox_to_anchor=(0.9, 1), loc=2, )
plt.title('Axis title')
plt.suptitle('Figure title')
# put an extra long y tick on to see that the bbox is accounted for
def y_formatter(y, pos):
if int(y) == 4:
return 'The number 4'
else:
return str(y)
plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter))
plt.xlabel('X axis')