python:如何使用matplotlib表示xaxis数据

2024-04-23 16:18:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用matplotlib绘制一个股票价格列表,但是我不知道如何在图表中正确显示相应的日期。csv中的数据是每日股价,但我只想在x轴上显示每两周的日期。股票日期和价格在两个不同的列表中,可以这样做吗?或者我应该用字典来代替,并且试着用这种方式来描述它?你知道吗

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()

Tags: csvinimportmainaspltfilenamewindow
2条回答

您应该从matplotlib网站check out this example。 看来你应该能做到以下几点:

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

现在在绘图中根本不使用x轴数据。您只需将“平均价格”提交给plt.绘图,因此它将只使用x轴的索引值。如果希望x轴显示日期信息,则应将日期数据格式化为datetime objects。这是一个example of how to format the x-axis记号,并在x轴上绘制日期图。你知道吗

另外,你对rounding to two decimal places的评论

相关问题 更多 >