如何使x轴使用日期而不是数字?

时间:2018-11-05 19:04:12

标签: python matplotlib

在Matplotlib中,如何使x轴图具有日期而不是数字?它的绘图可能使用类似02/201703/2017的图形。

这是我的代码:

import matplotlib.pyplot as plt
import datetime as dt

"""this program takes the YTD - daily prices of COST 
and calculates and graphs the SMA8 and SMA50"""


""" calulates the SMA"""


def get_sma(prices, nday): # calulates the SMA
    sma_data = [0] * len(prices)
    for i in range(nday, len(prices)):
        sma_data[i] = sum(prices[i - nday:i]) / nday
    return sma_data


"""opens file and prepares two lists of prices and dates"""


def read_data(): # opens file and prepares two lists of prices and dates
    global dates2
    global prices2
    filename = input("Please enter your file: ")
    f = open(filename)
    all_data = f.read()
    all_data_list = all_data.split('\n')
    data = [x.split(',') for x in all_data_list[1:] if x != '']
    dates2 = [d[0] for d in data]
    prices2 = [float(d[5]) for d in data]


"""plots the results
plots the sma8
plots sma50"""


def make_plot(dates, original_prices, sma10_prices, sma50_prices): # plots the results
    start = dt.datetime(2017, 1, 1)
    end = dt.datetime.now()
    plt.figure(figsize=(16, 7))
    plt.title('Costco Stock 1 Year Data and SMA')
    plt.plot(original_prices, linestyle='--', color='red', linewidth=2.0, label='COST') # plots the results
    plt.plot(sma10_prices, color='green', linestyle='-.', linewidth=3.0, label='SMA30') # plots sma 8
    plt.plot(sma50_prices, 'bo', markersize=1.2, label='SMA50') # plots sma 50
    plt.ylim(150, 250)
    plt.legend(loc='upper left')
    plt.savefig('costco.png')
    plt.show()


"""calls the functions
calls func 2
calls func 1 with ndays 8
call func 1 with ndays 50
calls func 3 for plotting"""


def main(): # calls the functions
    read_data() # calls func 2
    sma10 = get_sma(prices2, 10) # calls func 1 with ndays 8
    sma50 = get_sma(prices2, 50) #call func 1 with ndays 50
    make_plot(dates2, prices2, sma10, sma50) # calls func 3 for plotting


main()

0 个答案:

没有答案