【问题标题】:Bar chart matplotlib based on array of 8 rows with 5 values each条形图 matplotlib 基于 8 行数组,每行 5 个值
【发布时间】:2017-09-12 17:15:04
【问题描述】:

我在这个表单上有一个数组:

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]]

我想将其绘制为条形图。 x 轴上有 8 个点,每个点有 5 个条,高度对应于数组每行中的 5 个值。非常感谢任何帮助!

【问题讨论】:

标签: python-3.x numpy matplotlib bar-chart


【解决方案1】:

有两个使用plt.bar的选项。

单个相邻条

您可以以分组的方式将条形彼此相邻绘制,您需要根据数组中的列数确定条形的位置。

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

堆叠的条形

或者您可以将条形堆叠在一起,这样条形的底部从前一个的顶部开始。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 2015-02-08
    相关资源
    最近更新 更多