# Plot dataframe with two columns on the x axis

how would I plot the data below with the x axis as Year & Month? Each Year-month combination has a unique monthly count (Y). I am unsure how to proceed, given than they are in different columns, should I combine them first? Using matplotlib, you could create a custom tick formatter to show the right ticks. The year and month can either be fetched from the dataframe via the index (df.iloc[value]['Month']) or just be calculated.

Here is an example. You can also read the month name in the status bar when you hover over a position in the plot. The xticks (the positions where to have a tick with a label) can either be set automatically or manually.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

month_name = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

def format_func(value, tick_number):
value = int(value)
year = 2001 + value // 12
month = value % 12
# return f"{month+1}-{year}"
return f"{month_name[month]}-{year}"

N = 229
# create a dataframe resembling the example
df = pd.DataFrame({'Year': np.repeat(range(2001, 2021), 12)[:N],
'Month': np.tile(range(1, 13), N // 12 + 1)[:N],
'monthlycount': np.random.binomial(5000, .7, N)
})

plt.plot(df['monthlycount'], marker='o', c='crimson')
plt.xlim(0, N - 1)
plt.xticks(range(0, N, 12), rotation=20) # set major ticks every year
# plt.gca().set_xticks(range(0, N, 12), rotation=30)
plt.gca().set_xticks(range(0, N), minor=True)
plt.gca().xaxis.set_major_formatter(plt.FuncFormatter(format_func))
plt.tight_layout()
plt.show() 