简体   繁体   中英

python: how to represent x-axis data using matplotlib

I'm currently plotting a list of stock prices using matplotlib, however I'm not sure how to get the corresponding dates to show correctly in the graph. The data in the csv is daily stock prices but I would only want to show dates for every 2 weeks on the x-axis. The stock dates and prices are in 2 different lists, is it possible to do it this way? or should I use a dictionary instead and try and plot it that way?

import csv
import sys
import matplotlib.pyplot as plt


def main():
    filename = 'somefile.csv'
    with open(filename, newline='') as f:
        reader = csv.reader(f)
        next(reader, None)  # skips the column headers

        dates = list()
        prices = list()
        try:
            for row in reader:
                dates.append(row[0])
                prices.append(float(row[1]))  # converts prices to floats and saves in a new list.

            ma_window = 7

            reverse_prices = prices[::-1]

            average_reverse_prices = []

            r = len(prices) - ma_window + 1

            for i in range(r):
                interval = reverse_prices[i:(i + ma_window)]
                average = float(sum(interval)) / ma_window  # might want to round to 2 decimal places
                average_reverse_prices.append(average)

            average_prices = average_reverse_prices[::-1]
            print(average_prices)  

            plt.plot(average_prices)

            plt.xlabel('Date')
            plt.ylabel('Price')

            plt.show()

        except csv.Error as e:
            sys.exit('file {}, line {}: {}'.format(filename, reader.line_num, e))


if __name__ == '__main__':
    main()

You should check out this example from the matplotlib website. It seems that you should be able to do the following:

plt.xticks(range(0,len(average_prices), 14), dates[0:len(average_prices):14])

Right now you aren't using your x-axis data at all in the plot. You are only submitting "average_prices" to plt.plot, so it will just use the index value for the x-axis. If you want the x-axis to show your date information, you should format your date data as datetime objects . Here is an example of how to format the x-axis ticks and make a plot with dates in the x-axis.

Also, for your comment about rounding to two decimal places

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM