def make_date_ticks(ax, fs=12):
from matplotlib.dates import YearLocator, MonthLocator, DateFormatter
years = YearLocator()
months = MonthLocator(range(1, 13), bymonthday=1, interval=2)
yearsFmt = DateFormatter('%Y')
monthsFmt = DateFormatter("%b")
ax.tick_params(axis='x', which='major', labelsize=fs, pad=20)
ax.tick_params(axis='x', which='minor', pad=7)
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)
python类DateFormatter()的实例源码
smem_memory_monitor.py 文件源码
项目:cfme-performance
作者: redhat-performance
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def graph_all_miq_workers(graph_file_path, process_results, provider_names):
starttime = time.time()
file_name = graph_file_path.join('all-processes.png')
fig, ax = plt.subplots()
plt.title('Provider(s): {}\nAll Workers/Monitored Processes'.format(provider_names))
plt.xlabel('Date / Time')
plt.ylabel('Memory (MiB)')
for process_name in process_results:
if 'Worker' in process_name or 'Handler' in process_name or 'Catcher' in process_name:
for process_pid in process_results[process_name]:
dates = process_results[process_name][process_pid].keys()
rss_samples = list(process_results[process_name][process_pid][ts]['rss']
for ts in process_results[process_name][process_pid].keys())
vss_samples = list(process_results[process_name][process_pid][ts]['vss']
for ts in process_results[process_name][process_pid].keys())
plt.plot(dates, rss_samples, linewidth=1, label='{} {} RSS'.format(process_pid,
process_name))
plt.plot(dates, vss_samples, linewidth=1, label='{} {} VSS'.format(
process_pid, process_name))
dateFmt = mdates.DateFormatter('%m-%d %H-%M')
ax.xaxis.set_major_formatter(dateFmt)
ax.grid(True)
plt.legend(loc='upper center', bbox_to_anchor=(1.2, 0.1), fancybox=True)
fig.autofmt_xdate()
plt.savefig(str(file_name), bbox_inches='tight')
plt.close()
timediff = time.time() - starttime
logger.info('Plotted All Type/Process Memory in: {}'.format(timediff))
def plot_daily_inf_res(df, symbols=[], plot_top=0):
df = df.copy()
# data_nasdaq_top_100_preprocessed_merge.groupby('SYMBOL')
years = mdates.YearLocator() # every year
months = mdates.MonthLocator() # every month
years_fmt = mdates.DateFormatter('%Y')
df['max_pmi_is'] = df[[col for col in df.columns if 'pmi_is' in col]].max(axis=1)
if len(symbols) > 0:
df = df.loc[symbols]
if plot_top > 0:
idx = df.groupby('SYMBOL')['max_pmi_is'].max().sort_values(ascending=False).index[:plot_top].values
print idx
df = df.loc[list(idx)]
# df = df.reindex(index=idx)
fig, ax = plt.subplots(figsize=(15,5))
for key, grp in df.groupby('SYMBOL'):
print "key", key
# grp.reset_index()
# print grp.DATE
ax.plot(grp.DATE.reset_index(drop=True), grp['max_pmi_is'], label=key)
# grp['D'] = pd.rolling_mean(grp['B'], window=5)
# plt.plot(grp['D'], label='rolling ({k})'.format(k=key))
# datemin = (df.DATE.min().year)
# datemax = (df.DATE.max().year + 1)
# print datemin, datemax
# ax.set_xlim(datemin, datemax)
ax.set_ylim(0, 500)
plt.legend(loc='best')
plt.ylabel('PMI IS (-2)')
fig.autofmt_xdate()
plt.show()
def plot_trigger_criterion(transient):
fig, ax = plt.subplots(1)
# rotate and align the tick labels so they look better
for i in range(len(transient.trigger_criterion)):
ax.plot(transient.trigger_criterion_timestamps[i], transient.trigger_criterion[i], '.')
import matplotlib.dates as mdates
ax.fmt_xdata = mdates.DateFormatter('%H:%M:%S')
fig.autofmt_xdate()
return fig
def graph_all_miq_workers(graph_file_path, process_results, provider_names):
starttime = time.time()
file_name = graph_file_path.join('all-processes.png')
fig, ax = plt.subplots()
plt.title('Provider(s): {}\nAll Workers/Monitored Processes'.format(provider_names))
plt.xlabel('Date / Time')
plt.ylabel('Memory (MiB)')
for process_name in process_results:
if 'Worker' in process_name or 'Handler' in process_name or 'Catcher' in process_name:
for process_pid in process_results[process_name]:
dates = process_results[process_name][process_pid].keys()
rss_samples = list(process_results[process_name][process_pid][ts]['rss']
for ts in process_results[process_name][process_pid].keys())
vss_samples = list(process_results[process_name][process_pid][ts]['vss']
for ts in process_results[process_name][process_pid].keys())
plt.plot(dates, rss_samples, linewidth=1, label='{} {} RSS'.format(process_pid,
process_name))
plt.plot(dates, vss_samples, linewidth=1, label='{} {} VSS'.format(
process_pid, process_name))
dateFmt = mdates.DateFormatter('%m-%d %H-%M')
ax.xaxis.set_major_formatter(dateFmt)
ax.grid(True)
plt.legend(loc='upper center', bbox_to_anchor=(1.2, 0.1), fancybox=True)
fig.autofmt_xdate()
plt.savefig(str(file_name), bbox_inches='tight')
plt.close()
timediff = time.time() - starttime
logger.info('Plotted All Type/Process Memory in: {}'.format(timediff))
def generateActivityInfoForGroup(self, groupName):
timestampNow = int(time())
timestampYesterday = timestampNow - self.timestampSubtract
records = list(self.coll.find({ 'to': groupName, 'timestamp': { '$gt': timestampYesterday } }).sort([ ('timestamp', DESCENDING) ]))
fn = self.generateTmpFileName()
# Get histogram for activity
hist, bins = np.histogram([ x['timestamp'] for x in records ], bins=24)
center = (bins[:-1] + bins[1:]) / 2
datex = [ datetime.fromtimestamp(x) for x in center ]
pp.figure(figsize=(6,14))
ax = pp.subplot(2, 1, 1)
pp.plot_date(datex, hist, '.-')
pp.gcf().autofmt_xdate()
pp.xlabel(u'??????', fontproperties=self.prop)
pp.ylabel(u'??????', fontproperties=self.prop)
ax.xaxis.set_major_formatter(DateFormatter('%m-%d %H:%M'))
# Get bar chart for active users
pieDat = Counter([ x['from'] for x in records ])
pieDatSorted = sorted([ (k, pieDat[k]) for k in pieDat ],key=lambda x: x[1], reverse=True)
if len(pieDatSorted) > self.maxActivityInfoCount:
pieDatSorted = pieDatSorted[:self.maxActivityInfoCount]
ax = pp.subplot(2, 1, 2)
width = 0.7
x = np.arange(len(pieDatSorted)) + width
xText = [ xx[0] for xx in pieDatSorted ]
y = [ xx[1] for xx in pieDatSorted ]
pp.bar(x, y, width)
a = pp.gca()
a.set_xticklabels(a.get_xticks(), { 'fontProperties': self.prop })
pp.xticks(x, xText, rotation='vertical')
pp.xlabel(u'??', fontproperties=self.prop)
pp.ylabel(u'24?????', fontproperties=self.prop)
ax.set_xlim([ 0, len(xText) + 1 - width ])
pp.margins(0.2)
pp.savefig(fn)
return fn
def plotDatePrice(productID, productTitle, data):
# Data setup
x, y = [], []
for datapoint in data:
date = datapoint.split('|')[0]
price = float(datapoint.split('|')[1])
x.append(dt.datetime.strptime(date, '%Y-%m-%d'))
y.append(price)
x = matplotlib.dates.date2num(x)
x_np, y_np = np.array(x), np.array(y)
# Plot setup
ax = plt.figure(figsize=(6, 3)).add_subplot(111)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
ax.plot(x_np, y_np, color='lightblue', lw=2)
ax.margins(0.05)
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: ('$%i' % (x))))
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
plt.yticks(fontsize=8)
plt.ylim(ymin=min(y)*0.7, ymax=max(y)*1.3)
plt.title('Recent Price History\n'+productTitle, weight ='light', fontsize=12, y=1.08)
plt.xticks(rotation=40, fontsize=7)
plt.tight_layout()
plt.savefig(productID+'.png')
return productID+'.png'
# ----- Email Configuration ----------------------------------------------------
def plot_heart(day):
beats = session.query(models.Heart).filter(
and_(
Extract('day', models.Heart.date) == Extract('day', day),
Extract('month', models.Heart.date) == Extract('month', day),
Extract('year', models.Heart.date) == Extract('year', day),
)).all()
if not beats:
print("No data to plot.")
return
dates_x = [elem.date for elem in beats]
beats_y = [elem.value for elem in beats]
dates_x_less = [elem for index, elem in enumerate(dates_x) if index%10==0]
beats_y_less = [elem for index, elem in enumerate(beats_y) if index%10==0]
fig = plt.figure(figsize=(28, 5), dpi = 400, edgecolor='k')
ax = fig.add_subplot(111)
ax.set_xticks(dates_x_less)
ax.xaxis.grid(True)
ax.yaxis.grid(True)
xfmt = md.DateFormatter('%H:%M')
ax.xaxis.set_major_formatter(xfmt)
current_date = day.strftime("%B %d, %Y")
plt.suptitle(current_date, fontsize=20)
plt.xlabel('Time', fontsize=18)
plt.ylabel('Heart rate (BPM)', fontsize=16)
plt.subplots_adjust(bottom=0.2)
plt.xticks(rotation=90)
plt.plot(dates_x_less, beats_y_less, "o-")
plt.savefig(day.strftime("%Y-%m-%d")+'_heart.png', dpi=400,
bbox_inches='tight')
#plt.show()
plt.clf()
plt.cla() # clear axis
del fig
def plot_weight():
weight = session.query(models.Weight).order_by(desc(models.Weight.date)).\
filter().all()
if not weight:
print("No data to plot.")
return
dates_x = [elem.date for elem in weight]
weight_y = [elem.value for elem in weight]
fig = plt.figure(figsize=(40, 5), dpi = 400, edgecolor='k')
ax = fig.add_subplot(111)
ax.set_xticks(dates_x)
ax.xaxis.grid(True)
ax.yaxis.grid(True)
xfmt = md.DateFormatter('%d-%m-%Y')
ax.xaxis.set_major_formatter(xfmt)
plt.suptitle("Weight evolution", fontsize=20)
plt.xlabel('Time', fontsize=18)
plt.ylabel('Weight (kg)', fontsize=16)
plt.subplots_adjust(bottom=0.2)
plt.xticks(rotation=90)
plt.plot(dates_x, weight_y, "o-")
plt.savefig('weight.png', dpi=400, bbox_inches='tight')
#plt.show()
plt.clf()
plt.cla() # clear axis
del fig
def matplotlib_locator_formatter(timedelta, span=1):
"""
Compute appropriate locator and formatter for renderers
based on matplotlib, depending on designated time span.
"""
from matplotlib.dates import date_ticker_factory, DateFormatter
locator, formatter = date_ticker_factory(span)
# http://pandas.pydata.org/pandas-docs/stable/timedeltas.html
# https://stackoverflow.com/questions/16103238/pandas-timedelta-in-days
is_macro = timedelta <= Timedelta(days=1)
is_supermacro = timedelta <= Timedelta(minutes=5)
if is_macro:
#formatter = DateFormatter(fmt='%H:%M:%S.%f')
formatter = DateFormatter(fmt='%H:%M')
if is_supermacro:
formatter = DateFormatter(fmt='%H:%M:%S')
# Formatter overrides
#if formatter.fmt == '%H:%M\n%b %d':
# formatter = DateFormatter(fmt='%Y-%m-%d %H:%M')
# Labs
#from matplotlib.dates import AutoDateLocator, AutoDateFormatter, HOURLY
#locator = AutoDateLocator(maxticks=7)
#locator.autoscale()
#locator.intervald[HOURLY] = [5]
#formatter = AutoDateFormatter(breaks)
#formatter = date_format('%Y-%m-%d\n%H:%M')
# Default building blocks
#from matplotlib.dates import AutoDateFormatter, AutoDateLocator
#locator = AutoDateLocator()
#formatter = AutoDateFormatter(locator)
return locator, formatter
def plot_supply(request):
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter
currency = request.GET['currency']
genesis = crypto_data[currency.lower()]['genesis_date']
currency_name = crypto_data[currency.lower()]['name']
s = SupplyEstimator(currency)
try:
max_block = crypto_data[currency.lower()]['supply_data']['reward_ends_at_block']
end = s.estimate_date_from_height(max_block)
except KeyError:
end = genesis + datetime.timedelta(days=365 * 50)
x = list(date_generator(genesis, end))
y = [s.calculate_supply(at_time=z)/1e6 for z in x]
fig = Figure()
ax = fig.add_subplot(111)
ax.plot_date(x, y, '-')
ax.set_title("%s Supply" % currency_name)
ax.grid(True)
ax.xaxis.set_label_text("Date")
ax.yaxis.set_label_text("%s Units (In millions)" % currency.upper())
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
canvas = FigureCanvas(fig)
response = http.HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
def apply_date_formatting_to_axis(ax):
""" Format x-axis of input plot to a readable date format """
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(0), interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
return ax
def clear(self):
self.graph.cla()
zero = dt.datetime.fromtimestamp(0)
one = dt.datetime.fromtimestamp(1)
x, y = [zero, one], [-1, -1]
self.graph.set_xlim(zero, one)
self.graph.set_ylim(0, 1)
self.power_line, = self.graph.plot(x, y, color='red')
self.graph.xaxis.set_major_formatter(DateFormatter("%Y-%m-%d %H:%M:%S"))
self.graph.xaxis.set_major_locator(LinearLocator(numticks=6))
plt.setp(self.graph.get_xticklabels(), rotation=10)
self.graph.set_ylabel("Power (kW)")
def showPlot(date, data, file_name):
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import datetime
fig, ax = plt.subplots()
ax.xaxis.set_major_locator(mticker.MaxNLocator(5))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
print(date)
# print(data)
# date = [datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1, 1, 2, 0, 0), datetime.datetime(1, 1, 3, 0, 0), datetime.datetime(1, 1, 4, 0, 0)]
# data = [1, 2, 3, 4]
ax.plot(date, data)
# fig.plot([1, 2, 3], [1, 1, 1])
fig.savefig(file_name)
plt.close(fig)
# def showPlotMix(data, file_name='test.png'):
# fig, arr = plt.subplots(nrows=len(data), sharex=True)
# print('showPlotMix')
# for i, d in enumerate(data):
# # print(len(d[0]))
# for j, td in enumerate(d[0]):
# # print(len(td))
# print(len(d[1][j]))
# arr[i].plot(d[1][j], td)
# fig.savefig(file_name)
# plt.close(fig)
def showPlotMixSeparate(data, date, file_name='test.png'):
print('shopPlotMixSeparate')
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
fig, arr = plt.subplots()
ax1 = arr
ax1.xaxis.set_major_locator(mticker.MaxNLocator(5))
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
for j, td in enumerate(date):
arr.plot(td, data[j])
fig.savefig(file_name)
plt.close(fig)
def showPlotCompare(data, date, file_name):
print("showPlotCompare")
print(len(date))
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
fig, arr = plt.subplots(nrows=len(data), sharex=True)
for i, d in enumerate(data):
arr[i].xaxis.set_major_locator(mticker.MaxNLocator(7))
arr[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
# fig.suptitle('test title', fontsize=20)
# arr[i].set_title('ax1 title')
arr[i].plot(date, d)
fig.savefig(file_name)
plt.close(fig)
def showPlotLabelsCompare(data, date, labels, file_name):
print("showPlotCompare")
print(len(date))
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
fig, arr = plt.subplots(nrows=len(data), sharex=True)
for i, d in enumerate(data):
arr[i].xaxis.set_major_locator(mticker.MaxNLocator(7))
arr[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
# fig.suptitle('test title', fontsize=20)
arr[i].set_title(labels[i])
arr[i].plot(date, d)
fig.savefig(file_name)
plt.close(fig)
def showPlotCompareSeparate(data, date, file_name):
print("showPlotCompare")
print(len(date))
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
fig, arr = plt.subplots(nrows=len(data), sharex=True)
for i, d in enumerate(data):
arr[i].xaxis.set_major_locator(mticker.MaxNLocator(7))
arr[i].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
arr[i].plot(date[i], d)
fig.savefig(file_name)
plt.close(fig)
def chartFormatAxisX(self, ax, k_dict, p_dict):
""""""
ax.tick_params(axis='x', **k_dict['k_major_x'])
ax.tick_params(axis='x', **k_dict['k_minor_x'])
ax.xaxis.set_major_formatter(mdate.DateFormatter(p_dict['xAxisLabelFormat']))
self.setAxisScaleX(p_dict['xAxisBins']) # Set the scale for the X axis. We assume a date.
return ax
def set_date_axis(ax=None, dateformat='%d.%m.'):
"""Set DateFormatter for given AxesSubplot.
Parameters:
ax (AxesSubplot): Matplotlib axes.
dateformat (str): Format string for date labels on xaxis.
"""
if ax is None:
ax = plt.gca()
formatter = dates.DateFormatter(dateformat)
ax.xaxis.set_major_formatter(formatter)
ax.grid('on', which='both', linestyle='-')