【问题标题】:how to show all the x-axis label with panda/matplotlib如何使用 panda/matplotlib 显示所有 x 轴标签
【发布时间】: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,而是pandasdf.plot()。这不允许您很好地控制刻度标签。我不知道“显示所有标签”是什么意思,通常你有比空间更多的数据来为每个数据点显示一个标签。但是您当然可以通过使用适当的matplotlib.dates-locator 来增加滴答频率。作为起点有an example on the matplotlib page
  • 另见例如this question.

标签: python pandas matplotlib


【解决方案1】:

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

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

【讨论】:

  • 如果您要对某个答案投反对票,通常习惯上至少给出一个提示,说明为什么答案不充分。该问题没有 MCVE,因此可能存在误解。你想要 set_xticklabels() 而不是 set_xlabel() 因为你说的是​​轴标签。
猜你喜欢
  • 1970-01-01
  • 2020-10-24
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多