我正在尝试制作一个显示全年数据的图表。数据来自CSV文件(records.csv),如下所示:
month,data
2016-01,66
2016-02,68
2016-03,70
2016-04,72
2016-05,74
2016-06,76
2016-07,78
2016-08,80
2016-09,82
2016-10,84
2016-11,86
2016-12,88
我的代码如下:
import csv
from datetime import datetime
from matplotlib import pyplot as plt
def date_to_list(index):
""" save date to a list """
results = []
for row in data:
results.append(datetime.strptime(row[index], '%Y-%m'))
return results
def data_to_list(index):
""" save data to a list """
results = []
for row in data:
results.append(int(row[index]))
return results
filename = 'records.csv'
with open(filename) as f:
data = csv.reader(f)
header = next(data)
data = list(data)
# save data and date to list
records = data_to_list(1)
date = date_to_list(0)
plt.plot(date, records)
plt.show()
目前我正在努力解决以下两个问题:
答案 0 :(得分:1)
为了设置刻度的位置,您可以使用matplotlib.dates.MonthLocator
。为了使刻度具有特定格式,您可以使用matplotlib.dates.DateFormatter
。为了使ticklabel不重叠,您可以使用autofmt_xdate()
。为了没有边距,您可以使用plt.margins(x=0,y=0)
:
plt.gca().xaxis.set_major_locator(matplotlib.dates.MonthLocator())
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m"))
plt.gcf().autofmt_xdate()
plt.margins(x=0,y=0)
完整代码:
data = u"""month,data
2016-01,66
2016-02,68
2016-03,70
2016-04,72
2016-05,74
2016-06,76
2016-07,78
2016-08,80
2016-09,82
2016-10,84
2016-11,86
2016-12,88"""
import matplotlib.pyplot as plt
import matplotlib.ticker
import matplotlib.dates
import csv
from datetime import datetime
import io
def date_to_list(index):
""" save date to a list """
results = []
for row in data:
results.append(datetime.strptime(row[index], '%Y-%m'))
return results
def data_to_list(index):
""" save data to a list """
results = []
for row in data:
results.append(int(row[index]))
return results
with io.StringIO(data) as f:
data = csv.reader(f)
header = next(data)
data = list(data)
# save data and date to list
records = data_to_list(1)
date = date_to_list(0)
plt.plot(date, records)
plt.gca().xaxis.set_major_locator(matplotlib.dates.MonthLocator())
plt.gca().xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y-%m"))
plt.gcf().autofmt_xdate()
plt.margins(x=0,y=0)
plt.show()
答案 1 :(得分:0)