0

I have pulled in a dataset that I want to use, with columns named Date and Adjusted. Adjusted is just the adjusted percentage growth on the base month.

The code I currently have is:

x = data['Date']
y = data['Adjusted']

fig = plt.figure(dpi=128, figsize=(7,3))
plt.plot(x,y)

plt.title("FTSE 100 Growth", fontsize=25)
plt.xlabel("Date", fontsize=14)
plt.ylabel("Adjusted %", fontsize=14)
plt.show()

However, when I run it I get essentially a solid black line across the bottom where all of the dates are covering each other up. It is trying to show every single date, when obviously I only want to show major ones. That dates are in the format Apr-19, and the data runs from Oct-03 to May-20.

How do I limit the number of date ticks and labels to one per year, or any amount I choose? If you do have a solution, if you could respond with the edits made to the code itself that would be great. I've tried other solutions I've found on here but I haven't been able to get it to work.

Klevin
  • 1
  • 1
  • Does this answer your question? [Changing the "tick frequency" on x or y axis in matplotlib?](https://stackoverflow.com/questions/12608788/changing-the-tick-frequency-on-x-or-y-axis-in-matplotlib) – Edeki Okoh May 13 '20 at 21:28
  • I have tried the ax. methods previously, and I get `TypeError: cannot unpack non-iterable Figure object` when I simply add `fig, ax = plt.figure(dpi=128, figsize=(7,3))` , so the rest of the points are a no go at this point (with my ability).I've tried pretty much every thread on Stackoverflow relating to x ticks and haven't managed to find something that I could get to work. – Klevin May 13 '20 at 21:58

1 Answers1

0

dates module of matplotlib will do the job. You can control the interval by modifying the MonthLocator (It's currently set to 6 months). Here's how:

import pandas as pd
from datetime import date, datetime, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as md
import numpy as np
import matplotlib.ticker as ticker

x = data['Date']
y = data['Adjusted']
#converts differently formatted date to a datetime object
def convert_date(df):
    return datetime.strptime(df['Date'], '%b-%y')
data['Formatted_Date'] = data.apply(convert_date, axis=1)


# plot
fig, ax = plt.subplots(1, 1)
ax.plot(data['Formatted_Date'], y,'ok')

## Set time format and the interval of ticks (every 6 months)
xformatter = md.DateFormatter('%Y-%m') # format as year, month
xlocator = md.MonthLocator(interval = 6)

## Set xtick labels to appear every 6 months
ax.xaxis.set_major_locator(xlocator)

## Format xtick labels as YYYY:mm
plt.gcf().axes[0].xaxis.set_major_formatter(xformatter)
plt.title("FTSE 100 Growth", fontsize=25)
plt.xlabel("Date", fontsize=14)
plt.ylabel("Adjusted %", fontsize=14)
plt.show()

Example output:

example output

Sameeresque
  • 2,464
  • 1
  • 9
  • 22
  • Wow, that fixed it. Most of this is above my head however. A couple of questions if you don't mind: 1) How do I change this from a scatter to a line graph? 2) Is there a way to make the labels appear for the first month of each year? That way the label can just be `2018`, `2019` etc. Really appreciate your help! – Klevin May 14 '20 at 10:19
  • Hi! Welcome to SO. I see you're new to SO. If you feel an answer solved the problem, please mark it as 'accepted' by clicking the green checkmark. This helps keep the focus on older SO which still don't have answers. For your other questions: 1) remove the argument for `linestyle` 'ok' when plotting, 2) Change md.DateFormatter('%Y-%m') to ('%Y') while also setting interval to 12. – Sameeresque May 14 '20 at 12:33
  • Thanks for the help. One last question if that's ok. It appears the data is shifted a couple of marks left, so the 2004 tick actually represents Mar-04 rather than Jan-04 like you would expect it to. Do you know how to make the tick represent the first month of that year? I tried just deleting Oct-03 to Dec-03 but the 2004 tick is still aligned with Mar-04 rather than Jan-04. – Klevin May 14 '20 at 17:24
  • To set custom ticks I refer you to this [SO](https://stackoverflow.com/questions/60621751/reduce-x-axis-entries-in-an-area-plot-in-matplotlib/60621893#60621893) – Sameeresque May 14 '20 at 18:28
  • I appreciate the help, tried a whole manner of combinations of dates and xvals (4390.68 vs '4390.68' vs 2004-01 vs 2004 vs 01-2004) to no avail. Seems a bit silly to me that I have to list every single xval and xtick to make things line up. I tried, but couldn't get it to work. Thanks anyway. – Klevin May 14 '20 at 20:59