在sns relplot的facetgrid中注释文本

问题描述 投票:0回答:1

使用以下数据帧(mx):

    code    Growth  Value   Risk    Mcap
0   APOLLOHOSP  8   6   High    small
1   ANUP    8   7   High    small
2   SIS 4   6   High    mid
3   HAWKINCOOK  5   2   Low mid
4   NEULANDLAB  6   4   Low large
5   ORIENTELEC  7   9   Low mid
6   AXISBANK    2   3   Medium  mid
7   DMART   4   1   Medium  large
8   ARVIND  2   10  Medium  small
9   TCI 1   7   High    mid
10  MIDHANI 5   5   Low large
11  RITES   6   4   Medium  mid
12  COROMANDEL  9   9   High    small
13  SBIN    10  3   Medium  large

dataframe

我正在尝试创建一个sns relplot,它应该注释各个facetgrid中的散点图点。但是我得到的输出看起来像这样:

relplot

这里所有注释都在第一个构面中显示,其他构面中的点没有任何注释。

我尝试了以下代码:

p1 = sns.relplot(x="Growth", y="Value", hue="Risk",col="Mcap",data=mx,s=200,palette = ['r','g','y'])
ax = p1.axes[0,0]
for idx,row in mx.iterrows():
    x = row[1]
    y = row[2]
    text = row[0]
    ax.text(x+0.5,y,text, horizontalalignment='left')

请告知修改。预先感谢。

python pandas matplotlib annotations seaborn
1个回答
0
投票
此外,寻址row[0]row[1]等可能会使代码的可读性降低,并且在更改某些内容时不易适应。因此,最好将行directl分配给某些变量。

为了给名称留出空间,您可以将x限制向右扩展一点。

import pandas as pd import seaborn as sns from matplotlib import pyplot as plt data = [['APOLLOHOSP', 8, 6, 'High', 'small'], ['ANUP', 8, 7, 'High', 'small'], ['SIS', 4, 6, 'High', 'mid'], ['HAWKINCOOK', 5, 2, 'Low', 'mid'], ['NEULANDLAB', 6, 4, 'Low', 'large'], ['ORIENTELEC', 7, 9, 'Low', 'mid'], ['AXISBANK', 2, 3, 'Medium', 'mid'], ['DMART', 4, 1, 'Medium', 'large'], ['ARVIND', 2, 10, 'Medium', 'small'], ['TCI', 1, 7, 'High', 'mid'], ['MIDHANI', 5, 5, 'Low', 'large'], ['RITES', 6, 4, 'Medium', 'mid'], ['COROMANDEL', 9, 9, 'High', 'small'], ['SBIN', 10, 3, 'Medium', 'large']] mx = pd.DataFrame(data=data, columns=["code", "Growth", "Value", "Risk", "Mcap"]) plotnum = {'small': 0, 'mid': 1, 'large': 2} p1 = sns.relplot(x="Growth", y="Value", hue="Risk", col="Mcap", data=mx, s=200, palette=['r', 'g', 'y']) for ax in p1.axes[0]: ax.set_xlim(-0.9, max(mx["Growth"]) + 1.9) for idx, row in mx.iterrows(): print(row) text, x, y, _risk, mcap = row ax = p1.axes[0, plotnum[mcap]] ax.text(x + 0.5, y, text, horizontalalignment='left') plt.show()

resulting plot

© www.soinside.com 2019 - 2024. All rights reserved.