我正在努力让swarmplotot与熊猫一起工作.我有一个叫做SIAggs的3d numpy数组,我用这样的pandas切片:
rand_center = {('Random_dist'):SIAggs[:,:,1], ('Center_distance'):SIAggs[:,:,0]}
for key, value in rand_center.items():
rand_center[key] = pd.DataFrame(value)
sizes = {}
for i in range(size_iterations):
sizes.update({ (str(i+1)) : SIAggs[i,:,:] })
for key, value in sizes.items():
sizes[key] = pd.DataFrame(value)
df = pd.concat(sizes, rand_center, names = ['sizes', 'distance_measure'])
df.stack()
哪,当我打印DataFrame时给我:
sizes 1 2 3
distance_measure 0 1 0 1 0 1
0 -2.1881 1.262 -2.7001 1.493 -2.1381 1.626
1 -2.3671 1.699 -2.4431 1.208 -2.4571 1.186
2 -2.3071 0.716 -2.2841 1.122 -2.2441 1.396
3 -2.2521 0.967 -1.9451 1.496 -2.5261 1.690
4 -2.4651 1.800 -2.3421 1.500 -2.3571 0.985
5 -2.2011 1.409 -1.9921 0.160 -2.3701 1.114
6 -2.6911 0.915 -3.3301 1.510 -2.2561 1.676
7 -2.5751 1.128 -1.9931 0.941 -2.4411 1.605
8 -2.5321 1.651 -2.4751 1.145 -3.3541 1.228
9 -1.9741 0.886 -2.6671 1.196 -2.4581 1.321
这似乎是对的.
然后,当我尝试用swarmplot绘制它,我想要一个系列(按我的尺寸类别)配对(使用distance_measure的色调差异) – 基本上只使用seaborn
website中的第5个例子
ax = sns.swarmplot(x = "sizes", hue = "distance_measure", data = df, split=True)
plt.show()
抛出一个错误:
ax = sns.swarmplot(x = "sizes", hue = "distance_measure", data = df, split=True)
File "/Users/scottjg/anaconda/lib/python3.5/site-packages/seaborn/categorical.py", line 2679, in swarmplot
split, orient, color, palette)
File "/Users/scottjg/anaconda/lib/python3.5/site-packages/seaborn/categorical.py", line 1179, in __init__
self.establish_variables(x, y, hue, data, orient, order, hue_order)
File "/Users/scottjg/anaconda/lib/python3.5/site-packages/seaborn/categorical.py", line 147, in establish_variables
raise ValueError(err)
ValueError: Could not interpret input 'sizes'
任何帮助,将不胜感激.我似乎无法与熊猫/海鸟交朋友,但我想!
解决方法:
这是尝试生成您似乎正在寻找的图表,从您的示例数据开始:
df = pd.read_csv('swarm.csv', header=[0, 1], tupleize_cols=True, index_col=None)
cols = ['sizes', 'distance_measure']
df.columns = pd.MultiIndex.from_tuples(df.columns, names=cols)
sizes 1 2
distance_measure 0 1 0
0 -2.1881 1.262 -2.7001
1 -2.3671 1.699 -2.4431
2 -2.3071 0.716 -2.2841
3 -2.2521 0.967 -1.9451
4 -2.4651 1.800 -2.3421
用于seaborns演示的样本数据具有不同列中的变量,而不是使用MultiIndex,因此我进行相应的转换:
df = df.stack(cols).reset_index(cols).rename(columns={0: 'value'})
df.info()
Int64Index: 30 entries, 0 to 9
Data columns (total 3 columns):
sizes 30 non-null object
distance_measure 30 non-null object
value 30 non-null float64
df.head()
sizes distance_measure value
0 1 0 -2.1881
0 1 1 1.2620
0 2 0 -2.7001
1 1 0 -2.3671
1 1 1 1.6990
然后,下面的代码产生了样本#5:
ax = sns.swarmplot(x="sizes", y='value', hue="distance_measure", data=df, split=True)
plt.show()