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

I want to plot a bar chart or a histogram using 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 using plt.bar() with the alpha keyword as shown below.

The alpha controls the transparency of the bar.

N.B. when you have two overlapping bars, one with an alpha < 1, you will get a mixture of colours. 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.

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

e6391c62aaf931ae2bbb8f584b54e10a.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值