如何用panda / matplotlib显示所有x轴标签

时间:2017-11-30 02:27:47

标签: python pandas matplotlib

我为公司的股价历史做了一个简单的刮刀。我遇到的问题是当我使用matplotlib制作图形时,大多数x轴标签(在这种情况下为日期)都缺失了。如何强制pandas / matplotlib显示所有标签?

import pandas as pd
import urllib.request
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt

#open url and make soup
quote_url = "http://www.nasdaq.com/symbol/atnx/historical"
page = urllib.request.urlopen(quote_url)
soup = BeautifulSoup(page, 'html.parser')

#grab all the stock price data (except volume) for the last 2 weeks 
trs = soup.find('div', attrs={'id': 'historicalContainer'})\
    .find('tbody').find_all('tr')
temp_list = list()

for tr in trs:
    for td in tr:
        if td.string.strip():
            temp_list.append(td.string.strip())

list_of_list = [temp_list[i:i+5] for i in range(0, len(temp_list), 6)]

#only take data from the last 2 weeks for the sake of simplicity
list_of_list = list_of_list[:14]
data_dict = {sublist[0]: [float(n.replace(',', '')) for n in sublist[1:len(sublist)]] for sublist in list_of_list}

#create a pandas DataFrame for stock prices
df = pd.DataFrame(data_dict)
df.rename({0: 'Open', 1: 'High', 2: 'Low', 3: 'Close/Last'}, inplace=True)
#Transpose dataframe
df= df.T

#plot with matplotlib (most x labels are missing here)
df.plot()
plt.show()

感谢。

1 个答案:

答案 0 :(得分:-1)

根据我的经验,pandas.DataFrame.plot的格式很难完美。该函数返回轴的np.array。您可以在每个轴上使用 set_xlabel()

专业提示:如果轴是日期,我还建议使用 autofmt_xdate()