簡體   English   中英

如何在python中使用matplotlib繪制疊加條形圖?

[英]How to plot a superimposed bar chart using matplotlib in python?

我想使用 matplotlib 繪制條形圖或直方圖。 我不想要堆疊條形圖,而是兩個數據列表的疊加條形圖,例如我有以下兩個數據列表:

一些代碼開始:

import matplotlib.pyplot as plt
from numpy.random import normal, uniform

highPower   = [1184.53,1523.48,1521.05,1517.88,1519.88,1414.98,1419.34,
              1415.13,1182.70,1165.17]
lowPower    = [1000.95,1233.37, 1198.97,1198.01,1214.29,1130.86,1138.70,
               1104.12,1012.95,1000.36]

plt.hist(highPower, bins=10, histtype='stepfilled', normed=True,
         color='b', label='Max Power in mW')
plt.hist(lowPower, bins=10, histtype='stepfilled', normed=True,
         color='r', alpha=0.5, label='Min Power in mW')

我想根據兩個列表中的值數量繪制這兩個列表,以便我能夠看到每次讀數的變化。

您可以使用帶有alpha關鍵字的plt.bar()生成疊加條形圖,如下所示。

alpha控制條的透明度。

請注意,當您有兩個重疊的條形時,其中一個 alpha < 1,您將獲得混合顏色。 因此,即使圖例將其顯示為淺紅色,該條也會顯示為紫色。 為了緩解這種情況,我修改了其中一個條的寬度,這樣即使您的權力發生了變化,您仍然可以看到兩個條。

plt.xticks可用於設置圖表中 x-ticks 的位置和格式。

import matplotlib.pyplot as plt
import numpy as np

width = 0.8

highPower   = [1184.53,1523.48,1521.05,1517.88,1519.88,1414.98,
               1419.34,1415.13,1182.70,1165.17]
lowPower    = [1000.95,1233.37, 1198.97,1198.01,1214.29,1130.86,
               1138.70,1104.12,1012.95,1000.36]

indices = np.arange(len(highPower))

plt.bar(indices, highPower, width=width, 
        color='b', label='Max Power in mW')
plt.bar([i+0.25*width for i in indices], lowPower, 
        width=0.5*width, color='r', alpha=0.5, label='Min Power in mW')

plt.xticks(indices+width/2., 
           ['T{}'.format(i) for i in range(len(highPower))] )

plt.legend()

plt.show()

陰謀

基於@Ffisegydd 的回答,如果您的數據在 Pandas DataFrame 中,這應該可以很好地工作:

def overlapped_bar(df, show=False, width=0.9, alpha=.5,
                   title='', xlabel='', ylabel='', **plot_kwargs):
    """Like a stacked bar chart except bars on top of each other with transparency"""
    xlabel = xlabel or df.index.name
    N = len(df)
    M = len(df.columns)
    indices = np.arange(N)
    colors = ['steelblue', 'firebrick', 'darksage', 'goldenrod', 'gray'] * int(M / 5. + 1)
    for i, label, color in zip(range(M), df.columns, colors):
        kwargs = plot_kwargs
        kwargs.update({'color': color, 'label': label})
        plt.bar(indices, df[label], width=width, alpha=alpha if i else 1, **kwargs)
        plt.xticks(indices + .5 * width,
                   ['{}'.format(idx) for idx in df.index.values])
    plt.legend()
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if show:
        plt.show()
    return plt.gcf()

然后在 python 命令行中:

low = [1000.95, 1233.37, 1198.97, 1198.01, 1214.29, 1130.86, 1138.70, 1104.12, 1012.95, 1000.36]
high = [1184.53, 1523.48, 1521.05, 1517.88, 1519.88, 1414.98, 1419.34, 1415.13, 1182.70, 1165.17]
df = pd.DataFrame(np.matrix([high, low]).T, columns=['High', 'Low'],
                  index=pd.Index(['T%s' %i for i in range(len(high))],
                  name='Index'))
overlapped_bar(df, show=False)

matplotlib 中的重疊條形圖

它實際上比互聯網上的答案更簡單。

a = range(1,10)
b = range(4,13)
ind = np.arange(len(a))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x=ind, height=a, width=0.35,align='center')
ax.bar(x=ind, height=b, width=0.35/3,  align='center')

plt.xticks(ind, a)

plt.tight_layout()
plt.show()

在此處輸入圖片說明

暫無
暫無

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

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