Bar chart matplotlib based on array of 8 rows with 5 values each

十年热恋 提交于 2019-12-12 02:27:09

问题


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:


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.

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.

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()


来源:https://stackoverflow.com/questions/43445509/bar-chart-matplotlib-based-on-array-of-8-rows-with-5-values-each

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!