0

I make a simple scraper for a company's stock price history. The problem I have is when I use matplotlib to make graph, most of the x-axis labels (date in this case) are missing. How can I force pandas/matplotlib to display all labels?

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

Thanks.

Twisted Meadow
  • 443
  • 2
  • 7
  • Give a MCVE, including a plot of what you have, and some dummy data. – jonnybazookatone Nov 30 '17 at 05:39
  • You are not using matplotlib here directly, but pandas `df.plot()`. This does not allow you to have great control over the ticklabels. I do not know what you mean by "display all labels", usually you have much more data than space to show one label for each data point. But you may of course increase the tick frequency by using the appropriate `matplotlib.dates`-locator. As a starting point there is [an example on the matplotlib page](https://matplotlib.org/examples/api/date_demo.html). – ImportanceOfBeingErnest Nov 30 '17 at 09:56
  • Also see e.g. [this question](https://stackoverflow.com/questions/35663705/how-to-plot-time-on-y-axis-in-hm-format-in-matplotlib). – ImportanceOfBeingErnest Nov 30 '17 at 09:56

1 Answers1

-1

The formatting with pandas.DataFrame.plot is rarely perfect in my experience. The function returns an np.array of the axes. You can just use set_xlabel() on each axis after.

Pro tip: If the axis is dates I would also recommend to use autofmt_xdate()

Keith
  • 4,646
  • 7
  • 43
  • 72
  • If you are going to downvote an answer it is customary to at least give a hint as to why the answer is not adequate. The question does not have an MCVE so there could be a missinterpretation. Did you want set_xticklabels() insead of set_xlabel() because you said axis label. – Keith Nov 30 '17 at 17:56