使用matplotlib同时绘制两个直方图时,不透明度会产生误导 [英] Opacity misleading when plotting two histograms at the same time with matplotlib

查看:116
本文介绍了使用matplotlib同时绘制两个直方图时,不透明度会产生误导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个直方图,并且使用hist参数设置了不透明度:'alpha = 0.5'

Let's say I have two histograms and I set the opacity using the parameter of hist: 'alpha=0.5'

我绘制了两个直方图,但我得到了三种颜色!我了解从不透明的角度来看这是有道理的.

I have plotted two histograms yet I get three colors! I understand this makes sense from an opacity point of view.

但是!向某人显示具有三种颜色的两件事的图形非常令人困惑.我能以某种方式将每个垃圾箱的最小条形设置在前面而没有不透明性吗?

But! It makes is very confusing to show someone a graph of two things with three colors. Can I just somehow set the smallest bar for each bin to be in front with no opacity?

示例图

推荐答案

解决此问题的常用方法是使绘图之间有一些小间距.当为plt.hist提供多组数据时,默认情况下会这样做:

The usual way this issue is handled is to have the plots with some small separation. This is done by default when plt.hist is given multiple sets of data:

import pylab as plt

x = 200 + 25*plt.randn(1000)
y = 150 + 25*plt.randn(1000)
n, bins, patches = plt.hist([x, y])

您改为将其堆叠(可以在上面使用参数histtype='barstacked'进行此操作),但请注意顺序不正确.

You instead which to stack them (this could be done above using the argument histtype='barstacked') but notice that the ordering is incorrect.

可以通过单独检查每对点以查看哪个更大,然后使用zorder设置哪个是第一个来解决此问题.为简单起见,我使用上面代码的输出(例如n是x和y每个bin中点数的两个堆叠数组):

This can be fixed by individually checking each pair of points to see which is larger and then using zorder to set which one comes first. For simplicity I am using the output of the code above (e.g n is two stacked arrays of the number of points in each bin for x and y):

n_x = n[0]
n_y = n[1]
for i in range(len(n[0])):
    if n_x[i] > n_y[i]:
        zorder=1
    else:
        zorder=0
    plt.bar(bins[:-1][i], n_x[i], width=10)
    plt.bar(bins[:-1][i], n_y[i], width=10, color="g", zorder=zorder)

以下是生成的图像:

Here is the resulting image:

通过改变这样的顺序,图像确实看起来很奇怪,这可能就是为什么它没有实现并且需要黑客来完成的原因.我会坚持使用小分离法,任何习惯于这些图的人都假定它们采用相同的x值.

By changing the ordering like this the image looks very weird indeed, this is probably why it is not implemented and needs a hack to do it. I would stick with the small separation method, anyone used to these plots assumes they take the same x-value.

这篇关于使用matplotlib同时绘制两个直方图时,不透明度会产生误导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆