簡體   English   中英

Matplotlib在一張圖中繪制多個條形圖

[英]Matplotlib plot multiple bars in one graph

我有一個帶有多個具有不同場景的條形圖的圖,但是當我繪制它時,所有條形圖都是重復的。 請在下面找到我的代碼。

我知道我一次只使用列表中的一個值,但是當我嘗試使用data[0]傳遞整個子數組時,出現值不匹配錯誤:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

我究竟做錯了什么? 我看了PyPlot示例其他文章,都將數組傳遞給ax.bar

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

data = [[20, 35, 30, 40], [25, 40, 45, 30], 
        [15, 20, 35, 45], [10, 25, 40, 15], 
        [50, 20, 45, 55], [10, 55, 60, 20]]
data_std = [[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], 
            [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]]    

length = len(data)
x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

# Set plot parameters
fig, ax = plt.subplots()
width = 0.2 # width of bar
x = np.arange(length)

ax.bar(x, data[0][0], width, color='#000080', label='Case-1', yerr=data_std[0][0])
ax.bar(x + width, data[0][1], width, color='#0F52BA', label='Case-2', yerr=data_std[0][1])
ax.bar(x + (2 * width), data[0][2], width, color='#6593F5', label='Case-3', yerr=data_std[0][2])
ax.bar(x + (3 * width), data[0][3], width, color='#73C2FB', label='Case-4', yerr=data_std[0][3])

ax.set_ylabel('Metric')
ax.set_ylim(0,75)
ax.set_xticks(x + width + width/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('Scenario')
ax.set_title('Title')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()

結果是:

使用一個值繪制

您要按列繪制數據。 因此,將列表轉換為數組並選擇要繪制的相應列是有意義的。

import numpy as np
import matplotlib.pyplot as plt

data = np.array([[20, 35, 30, 40], [25, 40, 45, 30], 
                 [15, 20, 35, 45], [10, 25, 40, 15], 
                 [50, 20, 45, 55], [10, 55, 60, 20]])
data_std = np.array([[1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2], 
                     [1, 2, 1, 2], [1, 2, 1, 2], [1, 2, 1, 2]])    

length = len(data)
x_labels = ['A', 'B', 'C', 'D', 'E', 'F']

# Set plot parameters
fig, ax = plt.subplots()
width = 0.2 # width of bar
x = np.arange(length)

ax.bar(x, data[:,0], width, color='#000080', label='Case-1', yerr=data_std[:,0])
ax.bar(x + width, data[:,1], width, color='#0F52BA', label='Case-2', yerr=data_std[:,1])
ax.bar(x + (2 * width), data[:,2], width, color='#6593F5', label='Case-3', yerr=data_std[:,2])
ax.bar(x + (3 * width), data[:,3], width, color='#73C2FB', label='Case-4', yerr=data_std[:,3])

ax.set_ylabel('Metric')
ax.set_ylim(0,75)
ax.set_xticks(x + width + width/2)
ax.set_xticklabels(x_labels)
ax.set_xlabel('Scenario')
ax.set_title('Title')
ax.legend()
plt.grid(True, 'major', 'y', ls='--', lw=.5, c='k', alpha=.3)

fig.tight_layout()
plt.show()

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM