簡體   English   中英

從 seaborn swarmplot 中獲取繪制點的跨度

[英]Obtaining span of plotted points from seaborn swarmplot

我有以下數據:

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")

鏈接到 swarmplot 輸出

我如何獲得每個組的 x 跨度? 例如,父組的群圖的水平跨度范圍是多少?

您可以從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

這是圖:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM