Jonathan von Tamer
Jonathan von Tamer

Reputation: 57

How to make a barchart with multiple datas using matplotlib

I'm trying to do a barchart on python using matplotlib, but I do struggle even if I know that what I'm trying to do is very simple.

I have different variables of same lenght, imagine 4 lists :

run1 = [250,250,250,250]
run2 = [100,100,400,400]
run3 = [50,250,550,150]
run4 = [300,200,100,400]

And what I want is simply a graph with 4*4 bars. I want to group the first element of each list (here 250,100,50,300) and have four bars with different colors the height of which corresponding to the values on y axis. And then put a space, have again 4 bars with the next values (250,100,250,200) and so one.

How can I do that ?

Thank you.

Upvotes: 1

Views: 103

Answers (2)

pcu
pcu

Reputation: 1214

I guess the best way is to convert your data list to pandas DataFrame and plot:

import matplotlib.pyplot as plt
import pandas as pd

run1 = [250,250,250,250]
run2 = [100,100,400,400]
run3 = [50,250,550,150]
run4 = [300,200,100,400]

runs = pd.DataFrame({'Run 1': run1, 'Run 2': run2,
 'Run 3': run3, 'Run 4': run4})
runs.plot.bar()
plt.show()

enter image description here

Upvotes: 1

Sheldore
Sheldore

Reputation: 39062

This is one way of doing it. First merge all the four lists together to make use of NumPy indexing to get one element from each list.

Here alpha parameter which controls the transparency of the bars is important to use because if you use opaque bars alpha=1 then you will see only the highest bar because other bars will be hidden behind it. I used alpha=0.2. You can use any value you prefer.

import numpy as np
import matplotlib.pyplot as plt

run1 = [250,250,250,250]
run2 = [100,100,400,400]
run3 = [50,250,550,150]
run4 = [300,200,100,400]

run_all = np.stack((run1, run2, run3, run4))

for i in range(len(run_all)):
    plt.bar(range(4), run_all[i, :], alpha=0.2)

enter image description here

Upvotes: 0

Related Questions