在条形图上叠加箱线图

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

我正在尝试使用 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 bar-chart boxplot twinx
1个回答
6
投票

如何更改绘图的顺序,以便在条形图之后显示箱形图?例如:

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

这会给你:

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