python - 具有不同范围的分割 fiddle 图

标签 python matplotlib seaborn violin-plot

我正在尝试使用seaborn中的分割 fiddle 图来绘制具有不同范围的两个变量。

这是我到目前为止所做的:

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

df1 = pd.read_csv('dummy_metric1.csv')
df2 = pd.read_csv('dummy_metric2.csv')

fig, ax2 = plt.subplots()

sns.set_style('white')
palette1 = 'Set2'
palette2 = 'Set1'
colors_list = ['#78C850', '#F08030',  '#6890F0',  '#A8B820',  '#F8D030', '#E0C068', '#C03028', '#F85888', '#98D8D8']

ax1 = sns.violinplot(y=df1.Value,x=df1.modality,hue=df1.metric, palette=palette1, inner="stick")
xlim = ax1.get_xlim()
ylim = ax1.get_ylim()
for violin in ax1.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=ax1.transData))
ax1.set_xlim(xlim)
ax1.set_ylim(ylim)
ax1.set_title("dummy")
ax1.set_ylabel("metric1")
ax1.set_xlabel("Modality")
ax1.set_xticklabels(ax1.get_xticklabels(), rotation=45, ha='right')
ax1.legend_.remove()

ax2 = ax1.twinx() 

ax2 = sns.violinplot(y=df2.Value,x=df2.modality,hue=df2.metric, palette=palette2, inner=None)
xlim = ax2.get_xlim()
ylim = ax2.get_ylim()
for violin in ax2.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=ax2.transData))
ax2.set_xlim(xlim)
ax2.set_ylim(ylim)
ax2.set_ylabel("Metric2")
ax2.set_xticklabels(ax2.get_xticklabels(), rotation=45, ha='right')
ax2.legend_.remove()

fig.tight_layout()
plt.show()

但是,我无法使用 ax2 fiddle 的右侧部分。这是输出。

enter image description here

当我执行 violin.set_clip_path(plt.Rectangle((width/2, y0), width/2, height, transform=ax2.transData)) 时,我得到以下结果:

enter image description here

有人可以解释一下我错过了什么吗?另外,我该如何管理inner="stick"

TIA

最佳答案

这是一种使用 split=True 和虚拟数据强制进行空半分割的方法。对于左半部分,真实数据的 metric 设置为 1,虚拟数据的metric 设置为 2。右半部分反之亦然。我们需要确保所有数据帧对modality列使用相同的分类顺序,以避免混淆。

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

sns.set_style('white')
df1 = pd.DataFrame({'modality': pd.Categorical.from_codes(np.random.randint(0, 3, 30), ['a', 'b', 'c']),
                    'Value': np.random.rand(30) * 25 + 50})
df1['metric'] = 1
df1_dummy = pd.DataFrame({'modality': pd.Categorical.from_codes([0], ['a', 'b', 'c']), 'Value': [np.nan]})
df1_dummy['metric'] = 2

df2 = pd.DataFrame({'modality': pd.Categorical.from_codes(np.random.randint(0, 3, 100), ['a', 'b', 'c']),
                    'Value': np.random.randn(100).cumsum() / 10 + 1})
df2['metric'] = 2
df2_dummy = pd.DataFrame({'modality': pd.Categorical.from_codes([0], ['a', 'b', 'c']), 'Value': [np.nan]})
df2_dummy['metric'] = 1

ax1 = sns.violinplot(y='Value', x='modality', hue='metric', palette=['turquoise', 'red'],
                     inner="stick", split=True, data=pd.concat([df1, df1_dummy]))
ax1.legend_.remove()
ax1.set_ylabel('metric 1')

ax2 = ax1.twinx()
sns.violinplot(y='Value', x='modality', hue='metric', palette=['turquoise', 'red'],
               inner="stick", split=True, data=pd.concat([df2, df2_dummy]), ax=ax2)
ax2.set_ylabel('metric 2')

plt.tight_layout()
plt.show()

sns.violinplot splitting with different value ranges

PS:以下是对原始代码的可能修改:

  • 使用 plt.Rectangle((x0+width/2, y0), width/2, height) 将 fiddle 夹在 ax2 上
  • 使用 sns.violinplot()ax= 参数指示正确的子图
  • 不改变两个轴的 xlim 和 ylim
  • 确保两个数据帧对模态使用相同的分类顺序
  • 要剪辑“内部”线,对于 ax1:循环遍历线,获取它们的 x0x1,并缩短线到x0(x0+x1)/2
  • ax2类似:循环遍历各行,获取它们的x0x1,并将行缩短为(x0+ x1)/2x1
  • 更新 ax2 的图例,将其与 ax1 的图例合并,然后删除 ax1 的图例
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

df1 = pd.DataFrame({'modality': pd.Categorical.from_codes(np.random.randint(0, 3, 30), ['a', 'b', 'c']),
                    'Value': np.random.rand(30) * 25 + 50})
df1['metric'] = 1
df2 = pd.DataFrame({'modality': pd.Categorical.from_codes(np.random.randint(0, 3, 100), ['a', 'b', 'c']),
                    'Value': np.random.randn(100).cumsum() / 10 + 1})
df2['metric'] = 2

fig, ax1 = plt.subplots()

sns.set_style('white')
palette1 = 'Set2'
palette2 = 'Set1'

sns.violinplot(y=df1.Value, x=df1.modality, hue=df1.metric, palette=palette1, inner="stick", ax=ax1)
for violin in ax1.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=ax1.transData))
for line in ax1.lines:
    x = line.get_xdata()
    line.set_xdata([x[0], np.mean(x)])

ax1.set_ylabel("metric1")
ax1.set_xlabel("Modality")

ax2 = ax1.twinx()
sns.violinplot(y=df2.Value, x=df2.modality, hue=df2.metric, palette=palette2, inner="stick", ax=ax2)
ylim = ax2.get_ylim()
for violin in ax2.collections:
    bbox = violin.get_paths()[0].get_extents()
    x0, y0, width, height = bbox.bounds
    violin.set_clip_path(plt.Rectangle((x0 + width / 2, y0), width / 2, height, transform=ax2.transData))
for line in ax2.lines:
    x = line.get_xdata()
    line.set_xdata([np.mean(x), x[1]])
ax2.set_ylabel("Metric2")
ax2.set_xticklabels(ax2.get_xticklabels(), rotation=45, ha='right')
ax2.legend(handles=ax1.legend_.legendHandles + ax2.legend_.legendHandles, title='Metric')
ax1.legend_.remove()

fig.tight_layout()
plt.show()

关于python - 具有不同范围的分割 fiddle 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70442133/

相关文章:

python - kdeplot seaborn 中的自定义阴影调色板

python - seaborn gridplot/subplots 在同一行 ID 的第一列上显示一个变量,在第二列上显示另一个变量

matplotlib - 百分位分布图

python - 如何只返回 datetime.datetime 类型的日期部分?

python - 单个列表元素的属性 setter

Heroku 上的 Python - 发送给后台 worker

python - matplotlib 中的 subplots_adjust 在 IPython Notebook 中不起作用

python - 具有频率和计数的 matplotlib 直方图

python - 一次将所有打开的 matplotlib 图形保存在一个文件中

python - matplotlib 3 : 3D scatter plots with tight_layout