JED HK
JED HK

Reputation: 218

Heatmap with dates on x axis in Python

I have a dataframe where date is one column and the other columns are variables that can have values 1 or 0. Here is a mock example:

enter image description here

I would like to have a heatmap that has date along the x axis, the column headings (in this case names) on the y, and then fill the heatmap with a colour for 0s and another colour for 1s.

Code for making df:

df = pd.DataFrame(0, index=np.arange(10), columns=[['Mark', 'John', 'Ellen', 'Beth']])
for i in range(round(df.size/2)):
    row, col = np.random.randint(0,len(df)), np.random.randint(0,len(df.columns))
    df.iloc[row, col] = 1
df.insert(0, 'dates', pd.date_range(start='1/1/2018', periods=10))

Upvotes: 0

Views: 693

Answers (1)

Ran A
Ran A

Reputation: 774

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

df = pd.DataFrame(0, index=np.arange(10), columns=[['Mark', 'John', 'Ellen', 'Beth']])
for i in range(round(df.size/2)):
    row, col = np.random.randint(0,len(df)), np.random.randint(0,len(df.columns))
    df.iloc[row, col] = 1
df.insert(0, 'dates', (pd.date_range(start='1/1/2018', periods=10)).strftime("%Y-%m-%d"))
df=df.set_index("dates",drop=True)
df
plt.style.use("seaborn")
# 3. Plot the heatmap
plt.figure(figsize=df.shape)
heat_map = sns.heatmap(df.T) # ".T"to have the dates on x axis
plt.title( "HeatMap using Seaborn Method" )
plt.show()

result

Upvotes: 2

Related Questions