日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python dateformatter_Python dates.DateFormatter方法代码示例

發布時間:2025/4/5 python 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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;未經允許,請勿轉載。

總結

以上是生活随笔為你收集整理的python dateformatter_Python dates.DateFormatter方法代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。