繁体   English   中英

如何将自定义列顺序(在分类上)应用于熊猫箱线图?

[英]How to apply custom column order (on Categorical) to pandas boxplot?

编辑:这个问题出现在 2013 年的 Pandas ~0.13 中,并被版本 0.15-0.18 之间的 boxplot 的直接支持所取代(根据@Cireo 的最新答案;自从提出这个问题以来,pandas 也大大改进了对分类的支持。)


我可以在 Pandas DataFrame 中获得工资列的boxplot ...

train.boxplot(column='Salary', by='Category', sym='')

...但是我不知道如何定义在“类别”列上使用的索引顺序 - 我想根据另一个标准提供我自己的自定义订单

category_order_by_mean_salary = train.groupby('Category')['Salary'].mean().order().keys()

如何将自定义列顺序应用于箱线图列? (除了丑陋的列名加上前缀以强制排序)

'Category' 是一个字符串(真的,应该是一个分类的,但这是在 0.13 中,分类是三等公民)列采用 27 个不同的值: ['Accounting & Finance Jobs','Admin Jobs',...,'Travel Jobs'] . 所以它可以很容易地用pd.Categorical.from_array()分解

检查时,限制在pandas.tools.plotting.py:boxplot() ,它转换列对象而不允许排序:

我想我可以破解自定义版本的 pandas boxplot(),或者进入对象的内部。 并提交增强请求。

如果没有工作示例,很难说如何做到这一点。 我的第一个猜测是只添加一个带有您想要的订单的整数列。

一种简单的强力方法是一次添加每个箱线图。

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

df = pd.DataFrame(np.random.rand(37,4), columns=list('ABCD'))
columns_my_order = ['C', 'A', 'D', 'B']
fig, ax = plt.subplots()
for position, column in enumerate(columns_my_order):
    ax.boxplot(df[column], positions=[position])

ax.set_xticks(range(position+1))
ax.set_xticklabels(columns_my_order)
ax.set_xlim(xmin=-0.5)
plt.show()

在此处输入图片说明

编辑:这是在版本 0.15-0.18 之间添加直接支持后的正确答案


tl;dr :对于最近的熊猫 - 使用positions参数boxplot

添加一个单独的答案,这可能是另一个问题 - 感谢反馈。

我想在 groupby 中添加自定义列顺序,这给我带来了很多问题。 最后,我必须避免试图用boxplotgroupby对象,而是通过每插曲自己提供明确的立场。

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame()
df['GroupBy'] = ['g1', 'g2', 'g3', 'g4'] * 6
df['PlotBy'] = [chr(ord('A') + i) for i in xrange(24)]
df['SortBy'] = list(reversed(range(24)))
df['Data'] = [i * 10 for i in xrange(24)]

# Note that this has no effect on the boxplot
df = df.sort_values(['GroupBy', 'SortBy'])
for group, info in df.groupby('GroupBy'):
    print 'Group: %r\n%s\n' % (group, info)

# With the below, cannot use
#  - sort data beforehand (not preserved, can't access in groupby)
#  - categorical (not all present in every chart)
#  - positional (different lengths and sort orders per group)
# df.groupby('GroupBy').boxplot(layout=(1, 5), column=['Data'], by=['PlotBy'])

fig, axes = plt.subplots(1, df.GroupBy.nunique(), sharey=True)
for ax, (g, d) in zip(axes, df.groupby('GroupBy')):
    d.boxplot(column=['Data'], by=['PlotBy'], ax=ax, positions=d.index.values)
plt.show()

在我的最终代码中,确定位置的过程更加复杂,因为每个 sortby 值都有多个数据点,我最终不得不执行以下操作:

to_plot = data.sort_values([sort_col]).groupby(group_col)
for ax, (group, group_data) in zip(axes, to_plot):
    # Use existing sorting
    ordering = enumerate(group_data[sort_col].unique())
    positions = [ind for val, ind in sorted((v, i) for (i, v) in ordering)]
    ax = group_data.boxplot(column=[col], by=[plot_by], ax=ax, positions=positions)

实际上我被同样的问题困住了。 我通过制作地图并重置xticklabels来解决它,代码如下:

df = pd.DataFrame({"A":["d","c","d","c",'d','c','a','c','a','c','a','c']})
df['val']=(np.random.rand(12))
df['B']=df['A'].replace({'d':'0','c':'1','a':'2'})
ax=df.boxplot(column='val',by='B')
ax.set_xticklabels(list('dca'))

请注意,pandas 现在可以创建分类列。 如果您不介意在图表中显示所有列,或适当修剪它们,您可以执行以下操作:

http://pandas.pydata.org/pandas-docs/stable/categorical.html

df['Category'] = df['Category'].astype('category', ordered=True)

最近的熊猫似乎也允许positions从框架到轴一直传递。

正如 Cireo 指出的那样:

使用新的position=属性:

df.boxplot(column=['Data'], by=['PlotBy'], positions=df.index.values)

我知道这是精确的,但对像我这样的新手来说还不够清楚/总结

如果您对箱线图中的默认列顺序不满意,可以通过在箱线图中设置参数将其更改为特定顺序。

检查以下两个示例:

np.random.seed(0)
df = pd.DataFrame(np.random.rand(37,4), columns=list('ABCD'))

##
plt.figure()
df.boxplot()
plt.title("default column order")

##
plt.figure()
df.boxplot(column=['C','A', 'D', 'B'])
plt.title("Specified column order")

在此处输入图片说明

这听起来可能有点傻,但许多情节允许您确定顺序。 例如:

图书馆和数据集

import seaborn as sns
df = sns.load_dataset('iris')

具体顺序

p1=sns.boxplot(x='species', y='sepal_length', data=df, order=["virginica", "versicolor", "setosa"])
sns.plt.show()

这可以通过应用分类顺序来解决。 您可以自己决定排名。 我将举一个星期几的例子。

  • 提供工作日的分类顺序

    #List categorical variables in correct order weekday = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'] #Assign the above list to category ranking wDays = pd.api.types.CategoricalDtype(ordered= True, categories=Weekday) #Apply this to the specific column in DataFrame df['Weekday'] = df['Weekday'].astype(wDays) # Then generate your plot plt.figure(figsize = [15, 10]) sns.boxplot(data = flights_samp, x = 'Weekday', y = 'Y Axis Variable', color = colour)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM