你能用Python在雨云图上画一个半小提琴图和一个长方体图吗?

2024-10-06 14:33:01 发布

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

我使用以下代码创建了一个雨云图:

#雨点图

dx = 'Time Point'; dy = 'Score'; ort = "v"; pal = "Set2"; sigma = .2; 

f, ax = plt.subplots(figsize=(7, 5))

pt.RainCloud(x = dx, y = dy, data = df, palette = pal, bw = sigma,
             width_viol = .9, ax= ax, orient = ort, move = .2)

plt.title("")
plt.ylabel('Score', fontsize = 20) 
plt.xlabel('', fontsize = 20) 
plt.grid(color = 'w')

if savefigs: 
    plt.savefig('/Users/zeidanlab/Desktop/gv/rainplots/figure_tsc.png', bbox_inches='tight')

Raincloud Plot

我想知道是否有办法使方框图与分布图重叠


Tags: 代码timepltaxsigmapointscoredy
1条回答
网友
1楼 · 发布于 2024-10-06 14:33:01

下面是一种将半小提琴图、箱线图和条纹图结合起来的方法

半小提琴是通过提取其边界框并使用其一半来剪裁小提琴而创建的

移动条纹图的点以避免重叠

from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

sns.set_style('white')
tips = sns.load_dataset('tips')
palette = sns.cubehelix_palette(start=.5, rot=-.5, dark=0.3, light=0.7)
ax = sns.violinplot(y="day", x="total_bill", data=tips,
                    palette=palette,
                    scale="width", inner=None)
xlim = ax.get_xlim()
ylim = ax.get_ylim()
for violin in ax.collections:
    bbox = violin.get_paths()[0].get_extents()
    x0, y0, width, height = bbox.bounds
    violin.set_clip_path(plt.Rectangle((x0, y0), width, height / 2, transform=ax.transData))

sns.boxplot(y="day", x="total_bill", data=tips, saturation=1, showfliers=False,
            width=0.3, boxprops={'zorder': 3, 'facecolor': 'none'}, ax=ax)
old_len_collections = len(ax.collections)
sns.stripplot(y="day", x="total_bill", data=tips, color='dodgerblue', ax=ax)
for dots in ax.collections[old_len_collections:]:
    dots.set_offsets(dots.get_offsets() + np.array([0, 0.12]))
ax.set_xlim(xlim)
ax.set_ylim(ylim)
plt.show()

half violin with boxplot and stripplot

这里是另一个例子,在垂直方向上

from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np

sns.set_style('white')
iris = sns.load_dataset('iris')
palette = 'Set2'
ax = sns.violinplot(x="species", y="sepal_length", data=iris, hue="species", dodge=False,
                    palette=palette,
                    scale="width", inner=None)
xlim = ax.get_xlim()
ylim = ax.get_ylim()
for violin in ax.collections:
    bbox = violin.get_paths()[0].get_extents()
    x0, y0, width, height = bbox.bounds
    violin.set_clip_path(plt.Rectangle((x0, y0), width / 2, height, transform=ax.transData))

sns.boxplot(x="species", y="sepal_length", data=iris, saturation=1, showfliers=False,
            width=0.3, boxprops={'zorder': 3, 'facecolor': 'none'}, ax=ax)
old_len_collections = len(ax.collections)
sns.stripplot(x="species", y="sepal_length", data=iris, hue="species", palette=palette, dodge=False, ax=ax)
for dots in ax.collections[old_len_collections:]:
    dots.set_offsets(dots.get_offsets() + np.array([0.12, 0]))
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax.legend_.remove()
plt.show()

half violin with boxplot, vertical

相关问题 更多 >