matplotlib 在条形图上叠加箱线图

6bc51xsx  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(140)

我试图在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()
zbq4xfa0

zbq4xfa01#

如果只是更改图的顺序,使箱线图显示在条形图之后,如何?例如:

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

这将为您提供给予:

相关问题