pandas 带有熊猫和 Jupyter 笔记本的交互式箱线图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41667397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Interactive boxplot with pandas and Jupyter notebook
提问by Homunculus Reticulli
I have data in a pandas DataFrame, and I want to create an interactive boxplot that allows me to select the number of days, whilst plotting a boxplot for the values in each of the categories in the column 'category'
我在 Pandas DataFrame 中有数据,我想创建一个交互式箱线图,允许我选择天数,同时为“类别”列中每个类别的值绘制箱线图
This is what my code/data looks like so far:
这是我的代码/数据到目前为止的样子:
import numpy as np
import pandas as pd
categories=('A','B','C')
data = {
'days': np.random.randint(120, size=100),
'category': np.random.choice(categories, 100),
'value': 100.0 * np.random.random_sample(100)
}
df = pd.DataFrame(data)
print(df)
category days value
0 A 4 77.383981
1 A 31 63.011934
2 A 5 1.165061
3 C 59 23.588979
4 A 57 14.906734
5 C 106 33.366634
6 A 29 90.658570
7 B 25 16.137490
8 A 118 34.526302
9 C 76 4.111797
10 A 11 30.195917
.. ... ... ...
90 A 64 37.529774
91 A 76 3.771360
92 C 112 93.948775
93 C 14 34.855189
94 B 64 83.106007
95 A 10 78.346319
96 B 86 66.645889
97 A 46 12.969012
98 C 29 57.925427
99 A 59 34.526146
[100 rows x 3 columns]
I want to create a boxplot of the values for each of the categories (for a selected/specified number of days), with the different categories being plotted along the X-axis.
我想为每个类别(选定/指定的天数)创建一个值的箱线图,沿着 X 轴绘制不同的类别。
How do I do that using pandas (or matplotlib)?
我如何使用Pandas(或 matplotlib)做到这一点?
回答by ImportanceOfBeingErnest
You can simply filter the dataframe by the number of days and then plot the respective boxplot.
您可以简单地按天数过滤数据框,然后绘制相应的箱线图。
numer_of_days = 42
df_filtered= df.loc[df['days'] < numer_of_days] # use operators like ==, >=, <, etc.
df_filtered[["category", "value"]].boxplot( by="category", return_type='axes')
为了获得下拉字段,您可以使用该
ipywidgets.interact()
ipywidgets.interact()
函数,您可以向该函数提供一个绘制特定日期的数据框的函数。(在下面我将天数限制为 12,这样下拉菜单实际上就可以从中选择一天。)import numpy as np
import pandas as pd
from ipywidgets import interact
%matplotlib notebook
categories=('A','B','C')
data = {
'days': np.random.randint(12, size=100),
'category': np.random.choice(categories, 100),
'value': 100.0 * np.random.random_sample(100)
}
df = pd.DataFrame(data)
def select_days(number_of_days):
df_filtered= df.loc[df['days'] == int(number_of_days)]
ax = df_filtered[["category", "value"]].boxplot( by="category", return_type='axes')
ax["value"].set_title("Day " + number_of_days)
print df_filtered
days = [str(day) for day in np.arange(12)]
interact(select_days, number_of_days=days)