【发布时间】:2017-11-30 02:27:47
【问题描述】:
我为一家公司的股价历史做了一个简单的刮板。我遇到的问题是,当我使用 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()
谢谢。
【问题讨论】:
-
给出一个 MCVE,包括你所拥有的图表和一些虚拟数据。
-
你这里不是直接用matplotlib,而是pandas
df.plot()。这不允许您很好地控制刻度标签。我不知道“显示所有标签”是什么意思,通常你有比空间更多的数据来为每个数据点显示一个标签。但是您当然可以通过使用适当的matplotlib.dates-locator 来增加滴答频率。作为起点有an example on the matplotlib page。 -
另见例如this question.
标签: python pandas matplotlib