Pandas数据帧根据聚合结果绘制分组框图

2024-09-19 20:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想画一个方框图,但我没有原始数据,而是在Pandas数据框中聚合结果。在

是否仍有可能从汇总结果中绘制方框图?在

如果没有,我能得到的最接近的图是什么,来绘制最小值、最大值、平均值、中值、标准偏差等。我知道我可以用折线图来绘制它们,但我需要将盒形图分组/聚集。在

这是我的数据,绘图部分不见了。请帮忙。谢谢

import matplotlib.pyplot as plt

import numpy as np
import pandas as pd

df = pd.DataFrame({
        'group' : ['Tick Tick Tick', 'Tock Tock Tock', 'Tock Tock Tock', 'Tick Tick Tick']*3, # , ['Tock Tock Tock', 'Tick Tick Tick']*6,
        'person':[x*5 for x in list('ABC')]*4,
        'Median':np.random.randn(12),
        'StdDev':np.random.randn(12)
                   })
df["Average"]=df["Median"]*1.1
df["Minimum"]=df["Median"]*0.5
df["Maximum"]=df["Median"]*1.6
df["90%"]=df["Maximum"]*0.9
df["95%"]=df["Maximum"]*0.95
df["99%"]=df["Maximum"]*0.99

df

更新

我现在离得到结果又近了一步——我刚刚发现这个特性是available since matplotlib 1.4,我使用的是matplotlib 1.5,我测试了它和proved that it is working for me。在

问题是我不知道它为什么工作,以及如何调整我上面的代码来使用这样的新特性。我将在下面重新发布我的工作代码,希望有人能理解并把二加二放在一起。在

我的数据是中位数,平均值,最小值,90%,95%,99%,最大值和标准偏差,我希望能把它们都画出来。我查看了下面代码的logstats的数据结构,在for stats, label in zip(logstats, list('ABCD'))之后,发现它的字段是:

^{pr2}$

所以,从这个开始

box plot

对于bxp文档,我将按如下方式映射我的数据:

  • 威士忌:最小值
  • q1:中位数
  • 医学:一般
  • 平均值:90%
  • 问题3:95%
  • 威士忌:99%
  • 最大限度地作为传单

为了绘制它们,我只需做SELECT Minimum AS whislo, [90%] AS mean, [95%] as q3, [99%] as whishi这是最终结果:

raw_data = {'label': ['Label_01 Init', 'Label_02', 'Label_03', 'Label_04', 'Label_05', 'Label_06', 'Label_07', 'Label_08', 'Label_99'], 'whislo': [0.17999999999999999, 2.0299999999999998, 4.0800000000000001, 2.0899999999999999, 2.3300000000000001, 2.3799999999999999, 1.97, 2.6499999999999999, 0.089999999999999997], 'q3': [0.5, 4.9699999999999998, 11.77, 5.71, 12.460000000000001, 11.859999999999999, 13.84, 16.969999999999999, 0.29999999999999999], 'mean': [0.40000000000000002, 4.1299999999999999, 10.619999999999999, 5.0999999999999996, 10.24, 9.0700000000000003, 11.960000000000001, 15.15, 0.26000000000000001], 'whishi': [1.76, 7.6399999999999997, 20.039999999999999, 6.6699999999999999, 22.460000000000001, 21.66, 16.629999999999999, 19.690000000000001, 1.1799999999999999], 'q1': [0.28000000000000003, 2.96, 7.6100000000000003, 3.46, 5.8099999999999996, 5.4400000000000004, 6.6299999999999999, 8.9900000000000002, 0.16], 'fliers': [5.5, 17.129999999999999, 32.890000000000001, 7.9100000000000001, 32.829999999999998, 70.680000000000007, 24.699999999999999, 32.240000000000002, 3.3500000000000001]}
df = pd.DataFrame(raw_data, columns = ['label', 'whislo', 'q1', 'mean', 'q3', 'whishi', 'fliers'])

现在要挑战的是如何用多级分组来呈现我上面的框中数据框。如果多级分组太困难,让我们先从pd dataframe开始绘制,因为我的pddataframe与所需的np数组具有相同的字段。我试过了

fig, ax = plt.subplots()
ax.bxp(df.as_matrix(), showmeans=True, showfliers=True, vert=False)

但我有

...\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in bxp(self, bxpstats, positions, widths, vert, patch_artist, shownotches, showmeans, showcaps, showbox, showfliers, boxprops, whiskerprops, flierprops, medianprops, capprops, meanprops, meanline, manage_xticks)
   3601         for pos, width, stats in zip(positions, widths, bxpstats):
   3602             # try to find a new label
-> 3603             datalabels.append(stats.get('label', pos))
   3604             # fliers coords
   3605             flier_x = np.ones(len(stats['fliers'])) * pos

AttributeError: 'numpy.ndarray' object has no attribute 'get'

如果我使用ax.bxp(df.to_records(), ...,那么我将得到AttributeError: 'record' object has no attribute 'get'。在

好了,我终于开始工作了,从pd数据帧绘制,但不是多级分组,像这样:

df['fliers']=''
fig, ax = plt.subplots()
ax.bxp(df.to_dict('records'), showmeans=True, meanline=True, showfliers=False, vert=False) # shownotches=True, 
plt.show()

注意我上面的数据缺少med字段,您可以添加正确的字段,或者使用df['med']=df['q1']*1.2使其正常工作。在

import matplotlib
import matplotlib.pyplot as plt

import numpy as np
import pandas as pd

def test_bxp_with_ylabels():
    np.random.seed(937)
    logstats = matplotlib.cbook.boxplot_stats(
        np.random.lognormal(mean=1.25, sigma=1., size=(37,4))
    )
    print(logstats)
    for stats, label in zip(logstats, list('ABCD')):
        stats['label'] = label

    fig, ax = plt.subplots()
    ax.set_xscale('log')
    ax.bxp(logstats, vert=False)

test_bxp_with_ylabels()

bxp_with_ylabels


Tags: 数据importdfmatplotlibasstatsnp绘制
1条回答
网友
1楼 · 发布于 2024-09-19 20:26:27

在等待df澄清时,涉及:

dic = [{'cihi': 4.2781254505311281,
        'cilo': 1.6164348064249057,
        'fliers': array([ 19.69118642,  19.01171604]),
        'iqr': 5.1561885723613567,
        'mean': 4.9486856766955922,
        'med': 2.9472801284780168,
        'q1': 1.7655440553898782,
        'q3': 6.9217326277512345,
        'whishi': 12.576334012545718,
        'whislo': 0.24252084924003742}] 

以及数据应如何映射:

来自bxp文档:

^{pr2}$

然后,你只需:

fig, ax = plt.subplots(1,1)
ax.bxp([dic], showmeans=True)

所以您只需要找到一种方法来构建您的dic。请注意,它不会绘制您的std,对于胡须,您需要选择它们是增加到90%、95%还是99%,但您不能拥有所有值。在这种情况下,您需要在后面添加类似plt.hlines()的内容。在

高温

相关问题 更多 >