【问题标题】:Obtaining span of plotted points from seaborn swarmplot从 seaborn swarmplot 获取绘制点的跨度
【发布时间】:2016-04-14 06:30:08
【问题描述】:

我有以下数据:

import pandas as pd
import numpy as np

# Generate dummy data.
a = np.random.random(75)
b = np.random.random(75) - 0.6
c = np.random.random(75) + 0.75 

# Collate into a DataFrame
df = pd.DataFrame({'a': a, 'b': b, 'c': c}) 
df.columns = [list(['WT', 'MUT', 'WTxMUT']), list(['Parent', 'Parent', 'Offspring'])]
df.columns.names = ['Genotype', 'Status']
df_melt = pd.melt(df) 

我使用以下代码在 seaborn 中绘制它:

import seaborn as sb
sb.swarmplot(data = df_melt, x = "Status", y = "value", hue = "Genotype")

如何获得每个组的 x-span?例如,Parent 组的 swarmplot 的水平跨度范围是多少?

【问题讨论】:

  • 查看swarmplot返回的内容,你应该能够深入挖掘并找到包含他们数据的艺术家。

标签: python matplotlib seaborn swarmplot


【解决方案1】:

您可以从由swarmplot 创建的collections 获取信息。

swarmplot 实际上返回 matplotlib Axes 实例,从那里我们可以找到它创建的 PathCollections。获取位置,我们可以使用.get_offsets()

这是您的示例,已修改为查找和打印群限制,然后使用它们在群周围绘制一个框。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sb
from matplotlib.patches import Rectangle

# Generate dummy data.
a = np.random.random(75)
b = np.random.random(75) - 0.6
c = np.random.random(75) + 0.75 

# Collate into a DataFrame
df = pd.DataFrame({'a': a, 'b': b, 'c': c}) 
df.columns = [list(['WT', 'MUT', 'WTxMUT']), list(['Parent', 'Parent', 'Offspring'])]
df.columns.names = ['Genotype', 'Status']
df_melt = pd.melt(df) 

ax = sb.swarmplot(data = df_melt, x = "Status", y = "value", hue = "Genotype")

def getdatalim(coll):
    x,y = np.array(coll.get_offsets()).T
    try:
        print 'xmin={}, xmax={}, ymin={}, ymax={}'.format(
                x.min(), x.max(), y.min(), y.max())
        rect = Rectangle((x.min(),y.min()),x.ptp(),y.ptp(),edgecolor='k',facecolor='None',lw=3)
        ax.add_patch(rect)
    except ValueError:
        pass

getdatalim(ax.collections[0]) # "Parent"
getdatalim(ax.collections[1]) # "Offspring"

plt.show()

哪个打印:

xmin=-0.107313729132, xmax=0.10661092707, ymin=-0.598534246847, ymax=0.980441247759
xmin=0.942829146473, xmax=1.06105941656, ymin=0.761277608688, ymax=1.74729717464

这是这个数字:

【讨论】:

  • 很好的答案! small nitpick -- 将ax 作为getdatalim 的参数可能会很好。
  • 对于这个不是很必要的最小示例,但是如果您的用例需要,您当然可以包含它
猜你喜欢
  • 2016-09-09
  • 2017-10-03
  • 1970-01-01
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
  • 2021-05-01
  • 1970-01-01
  • 2021-05-24
相关资源
最近更新 更多