python dateformatter_Python dates.DateFormatter方法代码示例

本文整理汇总了Python中matplotlib.dates.DateFormatter方法的典型用法代码示例。如果您正苦于以下问题:Python dates.DateFormatter方法的具体用法?Python dates.DateFormatter怎么用?Python dates.DateFormatter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块matplotlib.dates的用法示例。

在下文中一共展示了dates.DateFormatter方法的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: plot_timeseries

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def plot_timeseries(DF, ax, name, startDate, stopDate, ylim=False):

"""

plots timeseries graphs

"""

# original time series

ax.plot(DF[name],color='#1f77b4')

ax.set_ylabel(name)

ax.set_ylim(ylim)

ax.set_xlim(pd.datetime.strptime(startDate,'%Y-%m-%d'),\

pd.datetime.strptime(stopDate,'%Y-%m-%d'))

# boxcar average

ax.plot(DF[name].rolling(180).mean(),color='red')

# make the dates exact

ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')

开发者ID:samsammurphy,项目名称:ee-atmcorr-timeseries,代码行数:19,

示例2: test_DateFormatter

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def test_DateFormatter():

import matplotlib.testing.jpl_units as units

units.register()

# Lets make sure that DateFormatter will allow us to have tick marks

# at intervals of fractional seconds.

t0 = datetime.datetime(2001, 1, 1, 0, 0, 0)

tf = datetime.datetime(2001, 1, 1, 0, 0, 1)

fig = plt.figure()

ax = plt.subplot(111)

ax.set_autoscale_on(True)

ax.plot([t0, tf], [0.0, 1.0], marker='o')

# rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 )

# locator = mpldates.RRuleLocator( rrule )

# ax.xaxis.set_major_locator( locator )

# ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) )

ax.autoscale_view()

fig.autofmt_xdate()

开发者ID:miloharper,项目名称:neural-network-animation,代码行数:24,

示例3: test_empty_date_with_year_formatter

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def test_empty_date_with_year_formatter():

# exposes sf bug 2861426:

# https://sourceforge.net/tracker/?func=detail&aid=2861426&group_id=80706&atid=560720

# update: I am no longer believe this is a bug, as I commented on

# the tracker. The question is now: what to do with this test

import matplotlib.dates as dates

fig = plt.figure()

ax = fig.add_subplot(111)

yearFmt = dates.DateFormatter('%Y')

ax.xaxis.set_major_formatter(yearFmt)

with tempfile.TemporaryFile() as fh:

assert_raises(ValueError, fig.savefig, fh)

开发者ID:miloharper,项目名称:neural-network-animation,代码行数:19,

示例4: test_empty_date_with_year_formatter

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def test_empty_date_with_year_formatter():

# exposes sf bug 2861426:

# https://sourceforge.net/tracker/?func=detail&aid=2861426&group_id=80706&atid=560720

# update: I am no longer believe this is a bug, as I commented on

# the tracker. The question is now: what to do with this test

import matplotlib.dates as dates

fig = plt.figure()

ax = fig.add_subplot(111)

yearFmt = dates.DateFormatter('%Y')

ax.xaxis.set_major_formatter(yearFmt)

with tempfile.TemporaryFile() as fh:

with pytest.raises(ValueError):

fig.savefig(fh)

开发者ID:holzschu,项目名称:python3_ios,代码行数:20,

示例5: graphRawFX

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def graphRawFX():

fig=plt.figure(figsize=(10,7))

ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)

ax1.plot(date,bid)

ax1.plot(date,ask)

#ax1.plot(date,((bid+ask)/2))

#ax1.plot(date,percentChange(ask[0],ask),'r')

ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))

#####

plt.grid(True)

for label in ax1.xaxis.get_ticklabels():

label.set_rotation(45)

plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)

#######

ax1_2 = ax1.twinx()

#ax1_2.plot(date, (ask-bid))

ax1_2.fill_between(date, 0, (ask-bid), facecolor='g',alpha=.3)

#ax1_2.set_ylim(0, 3*ask.max())

#######

plt.subplots_adjust(bottom=.23)

#plt.grid(True)

plt.show()

开发者ID:PythonProgramming,项目名称:Pattern-Recognition-for-Forex-Trading,代码行数:26,

示例6: graphRawFX

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def graphRawFX():

date,bid,ask = np.loadtxt('GBPUSD1d.txt', unpack=True,

delimiter=',',

converters={0:mdates.strpdate2num('%Y%m%d%H%M%S')})

fig=plt.figure(figsize=(10,7))

ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)

ax1.plot(date,bid)

ax1.plot(date,ask)

ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))

for label in ax1.xaxis.get_ticklabels():

label.set_rotation(45)

plt.subplots_adjust(bottom=.23)

plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)

plt.grid(True)

plt.show()

开发者ID:PythonProgramming,项目名称:Pattern-Recognition-for-Forex-Trading,代码行数:21,

示例7: graphRawFX

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def graphRawFX():

fig=plt.figure(figsize=(10,7))

ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)

ax1.plot(date,bid)

ax1.plot(date,ask)

ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))

plt.grid(True)

for label in ax1.xaxis.get_ticklabels():

label.set_rotation(45)

plt.gca().get_yaxis().get_major_formatter().set_useOffset(False)

ax1_2 = ax1.twinx()

ax1_2.fill_between(date, 0, (ask-bid), facecolor='g',alpha=.3)

plt.subplots_adjust(bottom=.23)

plt.show()

开发者ID:PythonProgramming,项目名称:Pattern-Recognition-for-Forex-Trading,代码行数:18,

示例8: get_graph

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def get_graph(df, coin_name, day_interval, dates=True):

import matplotlib.dates as mdates

from matplotlib import pyplot as plt

fig, ax = plt.subplots(figsize=(10, 5))

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%a'))

if dates:

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%b'))

plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=day_interval))

plt.gcf().autofmt_xdate()

plt.xlabel('Date', fontsize=14)

plt.ylabel('Price', fontsize=14)

plt.title('{} Price History'.format(coin_name))

y = df[coin_name]

plt.plot(df['date'], y)

开发者ID:andrebrener,项目名称:crypto_predictor,代码行数:18,

示例9: adjust_xlim

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def adjust_xlim(ax, timemax, xlabel=False):

xlim = mdates.num2date(ax.get_xlim())

update = False

# remove timezone awareness to make them comparable

timemax = timemax.replace(tzinfo=None)

xlim[0] = xlim[0].replace(tzinfo=None)

xlim[1] = xlim[1].replace(tzinfo=None)

if timemax > xlim[1] - timedelta(minutes=30):

xmax = xlim[1] + timedelta(hours=6)

update = True

if update:

ax.set_xlim([xlim[0], xmax])

for spine in ax.spines.values():

ax.draw_artist(spine)

ax.draw_artist(ax.xaxis)

if xlabel:

ax.xaxis.set_minor_locator(mdates.AutoDateLocator())

ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M\n'))

ax.xaxis.set_major_locator(mdates.DayLocator())

ax.xaxis.set_major_formatter(mdates.DateFormatter('\n%b %d'))

开发者ID:jxx123,项目名称:simglucose,代码行数:25,

示例10: ensemble_BG

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def ensemble_BG(BG, ax=None, plot_var=False, nstd=3):

mean_curve = BG.transpose().mean()

std_curve = BG.transpose().std()

up_env = mean_curve + nstd * std_curve

down_env = mean_curve - nstd * std_curve

# t = BG.index.to_pydatetime()

t = pd.to_datetime(BG.index)

if ax is None:

fig, ax = plt.subplots(1)

if plot_var and not std_curve.isnull().all():

ax.fill_between(

t, up_env, down_env, alpha=0.5, label='+/- {0}*std'.format(nstd))

for p in BG:

ax.plot_date(

t, BG[p], '-', color='grey', alpha=0.5, lw=0.5, label='_nolegend_')

ax.plot(t, mean_curve, lw=2, label='Mean Curve')

ax.xaxis.set_minor_locator(mdates.HourLocator(interval=3))

ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M\n'))

ax.xaxis.set_major_locator(mdates.DayLocator())

ax.xaxis.set_major_formatter(mdates.DateFormatter('\n%b %d'))

ax.axhline(70, c='green', linestyle='--', label='Hypoglycemia', lw=1)

ax.axhline(180, c='red', linestyle='--', label='Hyperglycemia', lw=1)

ax.set_xlim([t[0], t[-1]])

ax.set_ylim([BG.min().min() - 10, BG.max().max() + 10])

ax.legend()

ax.set_ylabel('Blood Glucose (mg/dl)')

# fig.autofmt_xdate()

return ax

开发者ID:jxx123,项目名称:simglucose,代码行数:33,

示例11: ensemblePlot

​点赞 6

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def ensemblePlot(df):

df_BG = df.unstack(level=0).BG

df_CGM = df.unstack(level=0).CGM

df_CHO = df.unstack(level=0).CHO

fig = plt.figure()

ax1 = fig.add_subplot(311)

ax2 = fig.add_subplot(312)

ax3 = fig.add_subplot(313)

ax1 = ensemble_BG(df_BG, ax=ax1, plot_var=True, nstd=1)

ax2 = ensemble_BG(df_CGM, ax=ax2, plot_var=True, nstd=1)

# t = df_CHO.index.to_pydatetime()

t = pd.to_datetime(df_CHO.index)

ax3.plot(t, df_CHO)

ax1.tick_params(labelbottom=False)

ax2.tick_params(labelbottom=False)

ax3.xaxis.set_minor_locator(mdates.AutoDateLocator())

ax3.xaxis.set_minor_formatter(mdates.DateFormatter('%H:%M\n'))

ax3.xaxis.set_major_locator(mdates.DayLocator())

ax3.xaxis.set_major_formatter(mdates.DateFormatter('\n%b %d'))

ax3.set_xlim([t[0], t[-1]])

ax1.set_ylabel('Blood Glucose (mg/dl)')

ax2.set_ylabel('CGM (mg/dl)')

ax3.set_ylabel('CHO (g)')

return fig, ax1, ax2, ax3

开发者ID:jxx123,项目名称:simglucose,代码行数:27,

示例12: matplotlib_locator_formatter

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

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

开发者ID:daq-tools,项目名称:kotori,代码行数:40,

示例13: __call__

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def __call__(self, x, pos=0):

fmt = self._get_fmt(x)

self._formatter = dates.DateFormatter(fmt, self._tz)

return self._formatter(x, pos)

开发者ID:ktraunmueller,项目名称:Computable,代码行数:6,

示例14: plot_supply

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

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

开发者ID:priestc,项目名称:MultiExplorer,代码行数:36,

示例15: plotTimeline

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def plotTimeline(dataTask, filename):

"""Build a timeline"""

fig = plt.figure()

ax = fig.gca()

worker_names = [x for x in dataTask.keys() if "broker" not in x]

min_time = getMinimumTime(dataTask)

ystep = 1. / (len(worker_names) + 1)

y = 0

for worker, vals in dataTask.items():

if "broker" in worker:

continue

y += ystep

if hasattr(vals, 'values'):

for future in vals.values():

start_time = [future['start_time'][0] - min_time]

end_time = [future['end_time'][0] - min_time]

timelines(ax, y, start_time, end_time)

#ax.xaxis_date()

#myFmt = DateFormatter('%H:%M:%S')

#ax.xaxis.set_major_formatter(myFmt)

#ax.xaxis.set_major_locator(SecondLocator(0, interval=20))

#delta = (stop.max() - start.min())/10

ax.set_yticks(np.arange(ystep, 1, ystep))

ax.set_yticklabels(worker_names)

ax.set_ylim(0, 1)

#fig.xlim()

ax.set_xlabel('Time')

fig.savefig(filename)

开发者ID:soravux,项目名称:scoop,代码行数:36,

示例16: get_inline_query_performance_statistics

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def get_inline_query_performance_statistics(session):

"""Plot statistics regarding performance of inline query requests."""

creation_date = func.cast(InlineQueryRequest.created_at, Date).label(

"creation_date"

)

# Group the started users by date

strict_search_subquery = (

session.query(

creation_date, func.avg(InlineQueryRequest.duration).label("count")

)

.group_by(creation_date)

.order_by(creation_date)

.all()

)

strict_queries = [("strict", q[0], q[1]) for q in strict_search_subquery]

# Combine the results in a single dataframe and name the columns

request_statistics = strict_queries

dataframe = pandas.DataFrame(

request_statistics, columns=["type", "date", "duration"]

)

months = mdates.MonthLocator() # every month

months_fmt = mdates.DateFormatter("%Y-%m")

# Plot each result set

fig, ax = plt.subplots(figsize=(30, 15), dpi=120)

for key, group in dataframe.groupby(["type"]):

ax = group.plot(ax=ax, kind="bar", x="date", y="duration", label=key)

ax.xaxis.set_major_locator(months)

ax.xaxis.set_major_formatter(months_fmt)

image = image_from_figure(fig)

image.name = "request_duration_statistics.png"

return image

开发者ID:Nukesor,项目名称:sticker-finder,代码行数:37,

示例17: __graph_over

​点赞 5

# 需要导入模块: from matplotlib import dates [as 别名]

# 或者: from matplotlib.dates import DateFormatter [as 别名]

def __graph_over(cls, date, over_data_dicts, under_data_dict, title, xlabel, ylabel, save_name=None):

figure = plt.figure(figsize=GarminDBConfigManager.graphs('size'))

# First graph the data that appears under

axes = figure.add_subplot(111, frame_on=True)

axes.fill_between(under_data_dict['time'], under_data_dict['data'], 0, color=Colors.c.name)

axes.set_ylim(under_data_dict['limits'])

axes.set_xticks([])

axes.set_yticks([])

# then graph the data that appears on top

colors = [Colors.r.name, Colors.b.name]

for index, _ in enumerate(over_data_dicts):

over_data_dict = over_data_dicts[index]

color = colors[index]

label = over_data_dict['label']

axes = figure.add_subplot(111, frame_on=False, label=label)

axes.plot(over_data_dict['time'], over_data_dict['data'], color=color)

axes.set_ylabel(label, color=color)

axes.yaxis.set_label_position(YAxisLabelPostion.from_integer(index).name)

if (index % 2) == 0:

axes.yaxis.tick_right()

axes.set_xticks([])

else:

axes.yaxis.tick_left()

limits = over_data_dicts[index].get('limits')

if limits is not None:

axes.set_ylim(limits)

axes.grid()

axes.set_title(title)

axes.set_xlabel(xlabel)

x_format = mdates.DateFormatter('%H:%M')

axes.xaxis.set_major_formatter(x_format)

if save_name:

figure.savefig(save_name)

plt.show()

开发者ID:tcgoetz,项目名称:GarminDB,代码行数:36,

注:本文中的matplotlib.dates.DateFormatter方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值