Home > Mobile >  Matplotlib: One X-Axis with two x labels of different type (int and string) in bar chart with one Y-
Matplotlib: One X-Axis with two x labels of different type (int and string) in bar chart with one Y-

Time:09-27

I am running through a problem on how to produce the attached image in matplotlib. I have n X-Axis (Users' most active minute) values in x1 and corresponding n Y-axis (Count) values. I can do the bar chart using these two axes. However, I have another variable Date which I want in the upper X-Axis (x2) exactly like the attached image. The important point is both x1 and x2 is of same length and as you can see the datatype of x1 is int and x2's datatype is datetime(/string).

x2 is NOT derived from x1 and the position of both the ticks and labels of x1 and x2 would be same. In brief, you can say X-Axis having two different labels with same Y-Axis. Any help would be greatly appreciated. Also, I would like to have the Y-Axis Count in the middle of each bar.

P.S: It would be nice if generic answer is provided as I have more than 5 datapoints unlike the attached image. So, I need a solution for n number of x1, n number of x2, and n number of Y values. Thank you!

This is what I am looking for

CodePudding user response:

Here is the code.

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

n = 15 

dates     = pd.date_range(start="2022-09-24 09:00",periods=n,freq="30T")
dates_str = [idate.strftime('%d-%m-%Y %H:%M') for idate in dates]

count= np.random.randint(low=300,high=1200,size=n)
ids =  np.random.randint(low=2000,high=10000,size=n)


X = range(n)
Y = count

fig = plt.figure(figsize=(10,7))
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()


width = 0.65 # the width of the bars 
ax1.bar(X, Y, width, color="#fa0872")
for i, v in enumerate(Y):
    ax1.text(i, v*0.6, str(v), color='k',ha="center" )
    
ax1.set_xticks(X)
ax1.set_xticklabels(ids)

ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(X)
ax2.set_xticklabels(dates_str,rotation = 45,ha='left', rotation_mode='anchor')

ax1.set_xlabel(r"User id")
ax1.set_ylabel(r"Count")
ax2.set_xlabel(r"Date")
plt.show()

enter image description here

  • Related