gpt4 book ai didi

不同 DataFrame 并排的 Pandas 箱线图

转载 作者:行者123 更新时间:2023-12-04 01:57:09 24 4
gpt4 key购买 nike

尽管网上有关于并排绘制箱线图的很好的例子。通过我的数据在两个不同的 pandas DataFrame 中设置的方式,并且已经有了总和子图,我无法管理使我的箱线图彼此相邻而不是重叠。

我的代码如下:

import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
mpl.use('agg')

fig, axarr = plt.subplots(3,sharex=True,sharey=True,figsize=(9,6))
month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
percentiles = [90,95,98]
nr = 0
for p in percentiles:
future_data = pd.DataFrame(np.random.randint(0,30,size=(30,12)),columns = month)
present_data = pd.DataFrame(np.random.randint(0,30,size=(30,12)),columns = month)

Future = future_data.as_matrix()
Present = present_data.as_matrix()

pp = axarr[nr].boxplot(Present,patch_artist=True, showfliers=False)
fp = axarr[nr].boxplot(Future, patch_artist=True, showfliers=False)

nr += 1

结果如下: Overlapping Boxplots

您能帮我看看如何确保这些框彼此相邻,以便我可以比较它们而不会受到重叠的困扰吗?

谢谢!

编辑:我稍微减少了代码,因此它可以像这样运行。

最佳答案

您需要手动定位条形图,即将位置作为数组提供给箱线图的 position 参数。在这里,将一个移动 -0.2,另一个移动 +0.2 到它们的整数位置是有意义的。然后,您可以调整它们的宽度,使其总和小于位置差。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

fig, axarr = plt.subplots(3,sharex=True,sharey=True,figsize=(9,6))
month = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']
percentiles = [90,95,98]
nr = 0
for p in percentiles:
future_data = pd.DataFrame(np.random.randint(0,30,size=(30,12)),columns = month)
present_data = pd.DataFrame(np.random.randint(0,30,size=(30,12)),columns = month)

Future = future_data.as_matrix()
Present = present_data.as_matrix()

pp = axarr[nr].boxplot(Present,patch_artist=True, showfliers=False,
positions=np.arange(Present.shape[1])-.2, widths=0.4)
fp = axarr[nr].boxplot(Future, patch_artist=True, showfliers=False,
positions=np.arange(Present.shape[1])+.2, widths=0.4)

nr += 1

axarr[-1].set_xticks(np.arange(len(month)))
axarr[-1].set_xticklabels(month)
axarr[-1].set_xlim(-0.5,len(month)-.5)

plt.show()

enter image description here

关于不同 DataFrame 并排的 Pandas 箱线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49775010/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com