【问题标题】:Overlay box plots on bars matplotlib/python条形图上的叠加箱线图 matplotlib/python
【发布时间】:2016-11-28 04:19:55
【问题描述】:

我正在尝试在 matplotlib 中使用单独的 y 轴在条形图上叠加一组箱形图。我在任何地方都找不到示例,并且已经尝试了所有我能想到的 ax.set_zorder() 和 ax2.set_alpha()。有没有办法只从箱形图中设置背景不透明? ax.patch.set_facecolor('None') 完全移除背景...

这是我尝试过的:

import matplotlib.pyplot as plt
import numpy as np

example_data = [1,2,1],[1,2,2,2],[3,2,1]

data = [i for i in example_data]

data_len = [len(i) for i in example_data]

labels = ['one','two','three']

plt.figure()

fig, ax = plt.subplots()

plt.boxplot(data)

ax.set_xticklabels(labels,rotation='vertical')


ax2 = ax.twinx()

ax2.bar(ax.get_xticks(),data_len,color='yellow', align='center')

ax2.set_zorder(1)

ax.set_zorder(2)

ax2.set_alpha(0.1)

ax.patch.set_facecolor('None')

plt.show()

提前感谢您的帮助。

【问题讨论】:

    标签: python matplotlib plot background multiple-axes


    【解决方案1】:

    改变绘图的顺序,使箱形图显示在条形图之后怎么样?例如:

    import matplotlib.pyplot as plt
    import numpy as np
    
    example_data = [[1,2,1], [1,2,2,2], [3,2,1]]
    data_len = [len(i) for i in example_data]
    labels = ['one','two','three']
    
    fig, ax = plt.subplots()
    ax.bar(range(1, len(data_len)+1), data_len, color='yellow', align='center')
    ax2 = ax.twinx()
    ax2.boxplot(example_data)
    ax2.set_ylim(ax.get_ylim())
    ax.set_xticklabels(labels, rotation='vertical')
    plt.show()
    

    这会给你:

    【讨论】:

    • 不错!谢谢,应该想到的。
    猜你喜欢
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 2015-12-25
    • 2019-05-30
    • 2020-09-26
    • 2019-12-07
    • 2016-09-02
    • 1970-01-01
    相关资源
    最近更新 更多