我有一个日期时间系列(称为日期),如下所示:
0 2012-06-26
1 2011-02-22
2 2012-06-06
3 2013-02-10
4 2004-01-01
5 2011-01-25
6 2015-11-02
我想在X轴上分散Y轴和月和年的日期。
我玩过pyplot.plot_date,但无法找出任何解决方案。
它只有this,只有Y轴上的日期。
有什么建议吗?
答案 0 :(得分:0)
看看matplotlib,它真的很有用。 这也可以帮助您开始绘图。
dates = [
'2012-06-26',
'2011-02-22',
'2012-06-06',
'2013-02-10',
'2004-01-01',
'2011-01-25',
'2015-11-02',
]
year = []
month = []
day = []
# Sorts your data in an useable dataset
def sort_data():
for i in range(len(dates)):
extracted_year = dates[i][0:4]
extracted_year = int(extracted_year)
year.append(extracted_year)
for j in range(len(dates)):
extracted_month = dates[j][5:7]
extracted_month = int(extracted_month)
month.append(extracted_month)
for k in range(len(dates)):
extracted_day = dates[k][8:10]
extracted_day = int(extracted_day)
day.append(extracted_day)
sort_data()
# Just checking if sort_date() worked correctly
print(year)
print(month)
print(day)
答案 1 :(得分:0)
到目前为止,我最好的解决方案是将年份和月份转换为浮点数,将天数转换为int:
from matplotlib import pyplot
dates = [
'2012-06-26',
'2011-02-22',
'2012-06-06',
'2013-02-10',
'2004-01-01',
'2011-01-25',
'2015-11-02',]
fig, ax = pyplot.subplots()
ax.scatter(date.apply(lambda x: float(x.strftime('%Y.%m'))),date.apply(lambda x: x.day), marker='o')
答案 2 :(得分:-1)
由于您的问题并不完全清楚,我假设您要分散最旧和最近年份之间所有输入日期时间条目的绘图(仅从给定输入中选择)。
此外,这是我第一次尝试" matplotlib"图书馆。所以,我希望以下答案会引导您达到预期的结果。
import datetime
import numpy
import matplotlib.pyplot as plt
from matplotlib.dates import MONDAY
from matplotlib.dates import DateFormatter, MonthLocator, WeekdayLocator
from matplotlib.dates import date2num
# Input datetime series.
dt_series = ["2012-06-26", "2011-02-22", "2012-06-06", "2013-02-10", "2004-01-01", "2011-01-25", "2015-11-02"]
mondays = WeekdayLocator(MONDAY)
months = MonthLocator(range(1, 13), bymonthday=1, interval=6)
monthsFmt = DateFormatter("%b'%y")
# Loop to create our own X-axis and Y-axis values.
# mths is for X-axis values, which are months along with year.
# dates is for Y-axis values, which are dates.
mths = list()
dates = list()
for dt in dt_series:
mths.append(date2num(datetime.datetime.strptime(dt.replace('-', ''), "%Y%m%d")))
dates.append(numpy.float64(float(dt.split('-')[2])))
fig, ax = plt.subplots(squeeze=True)
ax.plot_date(mths, dates, 'o', tz=None, xdate=True, ydate=False)
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsFmt)
ax.xaxis.set_minor_locator(mondays)
ax.autoscale_view()
ax.grid(True)
fig.autofmt_xdate()
plt.show()
我还建议您浏览一下我用作参考的链接: http://matplotlib.org/examples/pylab_examples/date_demo2.html
谢谢