简体   繁体   English

如何在python中使用matplotlib绘制叠加条形图?

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

I want to plot a bar chart or a histogram using matplotlib.我想使用 matplotlib 绘制条形图或直方图。 I don't want a stacked bar plot, but a superimposed barplot of two lists of data, for instance I have the following two lists of data with me:我不想要堆叠条形图,而是两个数据列表的叠加条形图,例如我有以下两个数据列表:

Some code to begin with :一些代码开始:

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

I want to plot these two lists against the number of values in the two lists such that I am able to see the variation per reading.我想根据两个列表中的值数量绘制这两个列表,以便我能够看到每次读数的变化。

You can produce a superimposed bar chart usingplt.bar() with the alpha keyword as shown below.您可以使用带有alpha关键字的plt.bar()生成叠加条形图,如下所示。

The alpha controls the transparency of the bar. alpha控制条的透明度。

NB when you have two overlapping bars, one with an alpha < 1, you will get a mixture of colours.请注意,当您有两个重叠的条形时,其中一个 alpha < 1,您将获得混合颜色。 As such the bar will appear purple even though the legend shows it as a light red.因此,即使图例将其显示为浅红色,该条也会显示为紫色。 To alleviate this I have modified the width of one of the bars, this way even if your powers should change you will still be able to see both bars.为了缓解这种情况,我修改了其中一个条的宽度,这样即使您的权力发生了变化,您仍然可以看到两个条。

plt.xticks can be used to set the location and format of the x-ticks in your graph. 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()

阴谋

Building on @Ffisegydd's answer , if your data is in a Pandas DataFrame, this should work nicely:基于@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()

And then in a python command line:然后在 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 中的重叠条形图

It is actually simpler than the answers all over the internet make it appear.它实际上比互联网上的答案更简单。

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.

相关问题 plot 条形图网格或包装条形图使用 python (matplotlib) - plot grid of bar charts or wrap bar chart using python (matplotlib) 使用pandas和Matplotlib中的csv数据在python中绘制条形图 - Plot bar chart in python using csv data in pandas & Matplotlib 如何在 python 中使用 matplotlib 对时间序列数据进行 plot 堆积条形图? - How to plot a stacked bar chart on time series data using matplotlib in python? 如何使用 python 中 matplotlib 中的相同 plt plot 并保存饼图和条形图 - How to plot and save pie chart and bar graph using same plt from matplotlib in python 如何使用 matplotlib 在 python 条形图中绘制可变数量的集合? - How do I plot a variable number of sets in a python bar chart using matplotlib? 如何使用matplotlib.pyplot在Python中绘制条形图? 参数高度必须为“ xxxx”或标量 - How to plot bar chart in Python using matplotlib.pyplot ? Argument height must be 'xxxx' or scalar 如何使用输入 *.txt 文件绘制一个非常简单的条形图(Python、Matplotlib)? - How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file? 使用matplotlib在python中绘制漂亮的条形图 - Pretty plot bar chart in python with matplotlib 在 python 中使用 matplotlib 绘制多个分组条形图 - Plot multiple grouped bar chart with matplotlib in python 使用matplotlib绘制条形图 - 类型错误 - plot a bar chart using matplotlib - type error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM