如何使用Matplotlib正确绘制叠加的3D条形?

问题描述 投票:1回答:1

我正在使用Matplotlib中的bar3d绘制3D直方图数据。我想在同一图上绘制实际数据和参考。我正在使用类似于this question中的一种技术,该技术由在同一轴上叠加的条组成。

这里是重现问题的最小脚本。

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D


value = 0.7
for i, value_reference in enumerate([0.66, 0.5]):
    fig = plt.figure()
    fig.suptitle('value = ' + str(value) + ', reference = ' + str(value_reference))
    # space between bar and reference bar
    s = 0.05
    # thickness of reference bar
    delta = 0.01
    # prepare 3D axis
    axes = fig.gca(projection='3d')
    # make the inner bar indicating the value
    axes.bar3d(
        s/2., s/2., 0., 1.-s, 1.-s, value,
        edgecolor='black')
    # surround it with outer bar indicating the reference
    axes.bar3d(
        0., 0., value_reference - delta/2., 1., 1., delta,
        color=(0, 0, 1, 0),
        edgecolor='black')
    # plt.show()
    fig.savefig('plot_reference_'+str(i)+'.png')

下面是该脚本的结果图。

reference value 0.66reference value 0.5

如您所见,通常是其中一根覆盖另一根。在第一种情况下,我们可以看到该条后面的参考水平,通常该条应覆盖该参考水平。在第二种情况下,我们完全看不到参考水平,因为它完全被条覆盖。

我认为原因是Matplotlib一张接一张地绘制整个条形图(就像在脚本中一样)。有没有一种方法可以向Matplotlib指示这两个条是重叠的,并且它们的面应该以特定顺序绘制?

用于生成这些图的环境

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.14.5
BuildVersion:   18F132

Python版本

$ python -V
Python 3.7.4

Matplotlib版本

$ pip show matplotlib
Name: matplotlib
Version: 3.1.2
Summary: Python plotting package
Home-page: https://matplotlib.org
Author: John D. Hunter, Michael Droettboom
Author-email: [email protected]
License: PSF
Location: /Users/marek/.pyenv/versions/3.7.4/lib/python3.7/site-packages
Requires: kiwisolver, cycler, pyparsing, python-dateutil, numpy
Required-by: 
python matplotlib plot
1个回答
0
投票

[第一个3D情节正在隐藏另一个情节。请问这是您的解决方案吗?

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

value = 0.7
for i, value_reference in enumerate([0.66, 0.5]):
    fig = plt.figure()
    fig.suptitle('value = ' + str(value) + ', reference = ' + str(value_reference))
    # space between bar and reference bar
    s = 0.05
    # thickness of reference bar
    delta = 0.02
    # prepare 3D axis
    axes = fig.gca(projection='3d')
    # make the inner bar indicating the value
    axes.bar3d(
        0., 0., value_reference - delta/2., 1., 1., delta, color='r', alpha=0.2,
        edgecolor='black')
    axes.bar3d(
        s/2., s/2., 0., 1.-s, 1.-s, value, color='b',alpha=0.2,
        edgecolor='black')
    # surround it with outer bar indicating the reference

    plt.show()

这清楚地显示了两个图:enter image description here

我不确定您是否可以要求Matplot按特定顺序绘制。似乎是关于zorder的热门讨论。您可以在这里阅读更多内容https://matplotlib.org/mpl_toolkits/mplot3d/faq.html

© www.soinside.com 2019 - 2024. All rights reserved.