pythonmatplotlibhistogrambinning

How to plot the graph using hist() function of matplotlib for "binned data"


I am new in matplotlib. I have data binned data.

         Level              Quantity
0      (199.533, 271.74]  (10.213, 39.4]
1      (199.533, 271.74]  (10.213, 39.4]
2      (54.903, 127.327]  (10.213, 39.4]
3     (127.327, 199.533]  (10.213, 39.4]
4     (127.327, 199.533]  (10.213, 39.4]
...                  ...             ...
5105   (54.903, 127.327]  (10.213, 39.4]
5106   (54.903, 127.327]    (39.4, 68.5]
5107   (54.903, 127.327]  (10.213, 39.4]
5108  (127.327, 199.533]  (10.213, 39.4]
5109   (54.903, 127.327]  (10.213, 39.4]

I want to make 2 histogram graph named "Level" and "Quantity" of each bin of "Equal width". I have tried this

import pandas as pd
import matplotlib.pyplot as plt

# Sample binned data for the two variables (Level and Quantity)
data = {
    'Level': ['(199.533, 271.74]', '(199.533, 271.74]', '(54.903, 127.327]', '(127.327, 199.533]', '(127.327, 199.533]'],......
    'Quantity': ['(10.213, 39.4]', '(10.213, 39.4]', '(10.213, 39.4]', '(10.213, 39.4]', '(10.213, 39.4]'],......
}

df_binned = pd.DataFrame(data)


plt.hist([df_binned['Level'], df_binned['Quantity']], bins=10, edgecolor='black', alpha=0.7, label=df_binned.columns)
plt.legend()
plt.title('Stacked Histograms of Binned Variables')
plt.xlabel('Bins')
plt.ylabel('Frequency')
plt.show()

It is not reading the bins in plt.hist() function

df_binned['Level']

df_binned['Quantity']

How i cann plot binned data? How to prepare the data for making histogram graph?


Solution

  • Need data preparation

    df_binned = pd.DataFrame(data)
    df_binned['Level']   = df_binned['Level'].dtype(str)
    df_binned['Quantity']=df_binned['Quantity'].dtype(str)