2017-02-19 78 views
1

我有一些代码表达的选举结果的在小提琴曲线形式的平衡:显示部分

plt.plot((0, 0), (0.85, 1.15), 'k-') 
p = plt.violinplot(np.array(results['Balance']),vert=False, bw_method='scott', widths=0.2,showextrema=False) 

该返回情节看起来像以下:

Violin Plot

我想以色“决定行”的该地块两侧,以反映的投票意向。像实物模型的东西如下所示:

enter image description here

我试图彼此独立地 例如标绘两个不同的集

p = plt.violinplot(np.array(results[results['Balance']>=0]['Balance']),vert=False, bw_method='scott', widths=0.2,showextrema=False) 
n = plt.violinplot(np.array(results[results['Balance']<0]['Balance']),vert=False, bw_method='scott', widths=0.2,showextrema=False) 

然后我可能使用的方法所讨论的here到颜色的每个PolyCollection不同。

但是返回的形状不再反映原始分布,所以在这种情况下我所寻找的帮助太大。

skewed distribution

没有人有实现更接近于我的有色样机任何意见或技术?

回答

1

问题是如果数据被剪切,小提琴图将计算不同的小提琴。所以人们需要在分隔线的两侧使用相同的小提琴。

想法可能是使用可通过path = p['bodies'][0].get_paths()[0]获得的小提琴的路径在分隔线两侧切出两个不同颜色的填图矩形的一部分。

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

#generate some data 
a = np.log(1+np.random.poisson(size=1500)) 
b = 0.2+np.random.rand(1500)*0.3 
c = 0.1+np.random.rand(1500)*0.6 
results=pd.DataFrame({'Balance':np.r_[a*b,-a*c]}) 

#create figure and axes 
fig, ax=plt.subplots() 
# sep is the point where the separation should occur 
sep = -0.05 
plt.plot((sep, sep), (0.85, 1.15), 'k-') 
# plot the violin 
p = plt.violinplot(np.array(results['Balance']),vert=False, 
        bw_method='scott', widths=0.2,showextrema=False) 
# obtain path of violin surrounding 
path = p['bodies'][0].get_paths()[0] 

#create two rectangles left and right of the separation line 
r = matplotlib.patches.Rectangle((results['Balance'].min(),0.85), 
        width=sep-results['Balance'].min(), height=0.3, facecolor="r") 
r2 = matplotlib.patches.Rectangle((sep,0.85), 
        width=results['Balance'].max()-sep, height=0.3, facecolor="b") 
# clip the rectangles with the violin path 
r.set_clip_path(path, transform=ax.transData) 
r2.set_clip_path(path, transform=ax.transData) 
ax.add_patch(r) 
ax.add_patch(r2) 

#optionally add edge around violin. 
s = matplotlib.patches.PathPatch(path, linewidth=1, edgecolor="k", fill=False) 
ax.add_patch(s) 
plt.show() 

enter image description here

+0

美丽!喜欢它,正是我所期待的 - 谢谢你的回答。 –