1

I have an array off this form:

data = [[19, 14, 6, 36, 3],
        [12, 12, 1, 32, 1],
        [18, 25, 0, 33, 0],
        [13, 19, 0, 32, 5],
        [12, 14, 0, 33, 0],
        [16, 14, 7, 30, 0],
        [11, 18, 5, 31, 2],
        [17, 11, 3, 46, 7]]

I want to plot it as a bar chart. There would be 8 points on the x-axis, each having 5 bars, with heights corresponding to the 5 values in each row of the array. Would super appreciate any help!

1

1 Answer 1

3

There are two obtions using plt.bar.

Single, adjacent bars

You can either plot the bars next to each other, in a grouped fashion, where you need to determine the bars' positions from the number of columns in the array.

enter image description here

import numpy as np
import matplotlib.pyplot as plt

data = np.array([[19, 14, 6, 36, 3],
                 [12, 12, 1, 32, 1],
                 [18, 25, 0, 33, 0],
                 [13, 19, 0, 32, 5],
                 [12, 14, 0, 33, 0],
                 [16, 14, 7, 30, 0],
                 [11, 18, 5, 31, 2],
                 [17, 11, 3, 46, 7]])
x = np.arange(data.shape[0])
dx = (np.arange(data.shape[1])-data.shape[1]/2.)/(data.shape[1]+2.)
d = 1./(data.shape[1]+2.)


fig, ax=plt.subplots()
for i in range(data.shape[1]):
    ax.bar(x+dx[i],data[:,i], width=d, label="label {}".format(i))

plt.legend(framealpha=1).draggable()
plt.show()

Stacked bars

Or you can stack the bars on top of each other, such that the bottom of the bar starts at the top of the previous one.

enter image description here

import numpy as np
import matplotlib.pyplot as plt

data = np.array([[19, 14, 6, 36, 3],
                 [12, 12, 1, 32, 1],
                 [18, 25, 0, 33, 0],
                 [13, 19, 0, 32, 5],
                 [12, 14, 0, 33, 0],
                 [16, 14, 7, 30, 0],
                 [11, 18, 5, 31, 2],
                 [17, 11, 3, 46, 7]])
x = np.arange(data.shape[0])

fig, ax=plt.subplots()
for i in range(data.shape[1]):
    bottom=np.sum(data[:,0:i], axis=1)  
    ax.bar(x,data[:,i], bottom=bottom, label="label {}".format(i))

plt.legend(framealpha=1).draggable()
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.