Python海生小提琴情节,不做我想做的事

2024-06-01 03:10:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我在看一些例子,但是所有的东西都需要一个数据帧。在

如果我有以下数据帧:

x = ["G","F","E","D","C","B"]
y = [3,14,45,47,34,15]

df = pd.DataFrame(
    {'Band': x,
     'Count': y,
    })

我想使用Count作为值,使用Band作为步骤来创建小提琴图,因此我已经完成了以下操作:

^{pr2}$

这就产生了:

enter image description here

但是,我想让Bandsy axis上,然后{}是每个等级的凸起大小。您只需要在y axis上使用continuous values吗?在

编辑:

我希望它看起来像:

enter image description here


Tags: 数据编辑dataframedfbandcount步骤例子
1条回答
网友
1楼 · 发布于 2024-06-01 03:10:53

小提琴图通常用于描述数据集的核密度。目前还不清楚离散数据集的内核密度应该是多少,但您当然可以通过将字母"B", "C", "D", ...映射到整数0,1,2,...并绘制小提琴来假设离散大小写是连续的。在

import matplotlib.pyplot as plt
import seaborn as sns

x = ["G","F","E","D","C","B"]
y = [3,14,45,47,34,15]

data = []
for i, yi in enumerate(y):
    data.extend([i]*yi)

sns.violinplot(y=data)
plt.yticks(range(len(x)), x)
plt.show()

enter image description here

这对信件的分发提供了一些一般性的提示。然而,为了定量使用,人们可能宁愿绘制条形图。在

^{pr2}$

enter image description here

当然,你可以用类似小提琴的方式来设计条形图,或者称之为“圣诞树情节”。在

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np

x = ["G","F","E","D","C","B"]
y = [3,14,45,47,34,15]

plt.barh(np.arange(len(x)), y, height=1, color="C0")
plt.barh(np.arange(len(x)), -np.array(y), height=1, color="C0")

plt.yticks(np.arange(len(x)), x)

# create strictly positive ticklabels
posfmt = mticker.FuncFormatter(lambda x,_: "{:g}".format(np.abs(x)))
plt.gca().get_xaxis().set_major_formatter(posfmt)
plt.show()

enter image description here

相关问题 更多 >