gpt4 book ai didi

python - 以阈值两侧的不同颜色(颜色)显示 matplotlib violinplot 的部分

转载 作者:太空宇宙 更新时间:2023-11-03 15:38:38 27 4
gpt4 key购买 nike

我有一些代码以 fiddle 图的形式表达选举结果的平衡:

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

我想为“决策线”两侧的该图着色以反射(reflect)投票意图。类似于下面所示的模型:

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设置不同的颜色。

但是返回的形状不再反射(reflect)原始分布,因此与我在这种情况下寻找的有用的形状相差太远。

skewed distribution

有人有任何想法或技术来实现更接近我的彩色模型的东西吗?

最佳答案

问题是,如果数据被剪切, fiddle 图将计算出不同的 fiddle 。因此,人们需要在分隔线的两侧使用同一把 fiddle 。

一个想法可能是使用 fiddle 的路径(可以通过 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

关于python - 以阈值两侧的不同颜色(颜色)显示 matplotlib violinplot 的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42330147/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com