5

I'm trying to plot time slots. I have two ndarrays of 'start' and 'end' points. I want to draw it as chunks on a figure. Keep in mind that the chunks are not consecutive and there are gaps between the slots.

Until now I have tried to use patches:

for x_1 , x_2 in zip(s_data['begin'].values ,s_data['end'].values):
ax1.add_patch(Rectangle((x_1,0),x_2-x_1,0.5)) 
plt.show()

But its only giving me hald blue figure.

While I want something like this

enter image description here

moh ro
  • 86
  • 8
RefiPeretz
  • 543
  • 5
  • 19

1 Answers1

12

The approach is correct. You just need to scale the axes such that the complete plot is within its range.

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"begin": [1,4,6,9], "end" : [3,5,8,12]})

fig, ax = plt.subplots()

for x_1 , x_2 in zip(df['begin'].values ,df['end'].values):
    ax.add_patch(plt.Rectangle((x_1,0),x_2-x_1,0.5))

ax.autoscale()
ax.set_ylim(-2,2)
plt.show()

enter image description here

It is worth noting that matplotlib has a function broken_barh, which simplifies the creation of such charts.

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({"begin": [1,4,6,9], "end" : [3,5,8,12]})

fig, ax = plt.subplots()

ax.broken_barh(list(zip(df["begin"].values, (df["end"] - df["begin"]).values)), (0, 0.5))

ax.set_ylim(-2,2)
plt.show()

Giving the same diagram as the above.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712