Python plot monthlywise data between two variables

Viewed 69

I want to plot the data between two variables. In that I want to plot monthly data using a special color.

My code and expectedoutput:

import matplotlib.pyplot as plt

df
             A     B
2019-01-01   10   20
2019-01-02   20   30
2019-02-01   10   15
2019-02-02   20   40
2019-03-01   12   32
2019-03-02   5    14

plt.plot(df['A'],df['B'])
plt.show()

My current plot plots all the data as usual but I am expecting something different as given below. My expected output:

enter image description here 2019-03-01 10 20

2 Answers

You can do something like this:

markers = 'dsxo'
months = pd.to_datetime(df.index).to_period('M')

for i, (k,d) in enumerate(df.groupby(months) ):
    plt.plot(d['A'],d['B'], label=k, marker=markers[i])

plt.legend()

Output:

enter image description here

Check this code:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv('data.csv')

df['Month'] = df.index.map(lambda x: x[:-3])

fig, ax = plt.subplots(1, 1, figsize = (6, 6))
for month in df['Month'].unique():
    ax.plot(df[df['Month'] == month]['A'],
            df[df['Month'] == month]['B'],
            label = month)

plt.legend()
plt.show()

that gives this graph:

enter image description here

Related