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?

enter image description here


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)



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.