【问题标题】:How to plot a superimposed bar chart using matplotlib in python?如何在 python 中使用 matplotlib 绘制叠加条形图?
【发布时间】:2014-06-11 03:52:44
【问题描述】:

我想使用 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')

我想将这两个列表与两个列表中的值的数量进行对比,以便我能够看到每次读数的变化。

【问题讨论】:

  • 是的,我将其发布在问题的编辑中
  • 看看numpy.cumsum()pyplot.hist()...
  • pyplot.hist() 我该如何使用它?
  • @Ffisegydd 你能提供什么帮助吗?

标签: python numpy matplotlib plot histogram


【解决方案1】:

您可以使用plt.bar()alpha 关键字生成叠加条形图,如下所示。

alpha 控制栏的透明度。

注意当您有两个重叠的条时,其中一个的 alpha

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

【讨论】:

  • 列表中没有超过2000的值,那么这个条形图怎么显示大于2000的值,x轴上的标签必须是[1,2,3,4 ,.....,10] 但它以 2 为增量显示
  • 我不希望它们堆叠在一起,而是它们应该相互叠加,较低的值应该占据较高值的条形区域
  • 太好了,这行得通,也谢谢你的解释 :) 但是如何将 x 轴上的刻度修改为 T1、T2、T3 等等
  • 我添加了一个示例,说明如何将 x-ticks 设置为“T1”、“T2”等。但是我建议您在开始时充分解释您的问题(不要在进行时添加更多子问题)或只是针对扩展问题提出一个新问题。
  • 当我运行这段代码时,红条显示在蓝条的右侧,而不是中间。可以更新代码吗?
【解决方案2】:

以@Ffisegydd 的answer 为基础,如果您的数据在 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)

【讨论】:

  • 试试这个代码,它显示了两次条形图,可以编辑代码使其只显示一次图表吗?
  • 您还如何更改此图表的无花果大小?我似乎无法以标准方式改变它
  • @CathaBrady 你在用蜘蛛吗?你的python环境是什么?此代码仅适用于带有 matplotlib 的完整 python 环境,并且它的后端已为您的操作系统或环境正确配置。您必须在 Jupyter Notebook 中做一些稍微不同的事情。
  • 不知何故在我的环境中没有黑暗。我还尝试将其修改为 barh,因为我认为垂直条看起来更适合我的数据,但我的尝试破坏了索引 ?
【解决方案3】:

它实际上比互联网上的答案更简单。

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

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 2019-01-31
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2022-08-06
    • 1970-01-01
    • 2015-06-20
    • 2020-01-18
    相关资源
    最近更新 更多