Generating an histogram with Matplotlib using a dataframe for x and y

Viewed 47

I'm generating a simple line chart with Matplotlib, here is my code:

fig = plt.figure(facecolor='#131722',dpi=155, figsize=(8, 4))
ax1 = plt.subplot2grid((1,2), (0,0), facecolor='#131722')

for x in OrderedList:
    rate_buy = []
    total_buy = []

    for y in x['data']['bids']:
        rate_buy.append(y[0])
        total_buy.append(y[1])

    rBuys = pd.DataFrame({'buy': rate_buy})
    tBuys = pd.DataFrame({'total': total_buy})

    ax1.plot(rBuys.buy, tBuys.total, color='#0400ff', linewidth=0.5, alpha=1)
    ax1.fill_between(rBuys.buy, 0, tBuys.total, facecolor='#0400ff', alpha=1)

Which gives me the following output:

And here is the data i used in the dataframe:

     buy
0   9611
1   9610
2   9609
3   9608
4   9607
5   9606
6   9605
7   9604
8   9603
9   9602
10  9601
11  9600
12  9599
        total
0    3.033661
1    3.295753
2    3.599813
3   22.305765
4   22.987476
5   30.975145
6   39.492845
7   42.828580
8   46.677708
9   49.533740
10  50.925840
11  61.396243
12  61.921523

I want to get the same output of the image, but with an histogram chart or whatever it's similar to that, where the height of the column on the y axis is retrieved from the total dataframe and the x axis position is retrieved from the buy dataframe. So the first element will have position x=9611 and y=3.033661

Is it possible to do that with Matplotlib? I tried to use hist, but it doesn't allow me to set both the x and the y axis

1 Answers

Pandas uses matplotlib as well, and the API is very easy once you have the dataframe.

Here is an example.

d =    {
         'buy':[
             9611,
             9610,
             9609,
             9608,
             9607,
             9606,
             9605,
             9604,
             9603,
             9602,
             9601,
             9600,
             9599
         ],
         'total':[
             3.033661,
             3.295753,
             3.599813,
             22.305765,
             22.987476,
             30.975145,
             39.492845,
             42.828580,
             46.677708,
             49.533740,
             50.925840,
             61.396243,
             61.921523
         ]
     }

df = pd.DataFrame(d)

df = df.sort_values(by=['buy']) #remember to sort your x values!
df.plot(kind='bar', x='buy', y='total', width=1)
plt.show()

enter image description here

Related