在特定位置绘制一条线/在seaborn中注释FaceGrid

2024-03-29 15:22:45 发布

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

A已经用seaborn的Facetgrid以以下方式生成了一个箱线图

# Import the dataset
tips = sns.load_dataset("tips")

# Plot using FacetGrid, separated by smoke
plt.style.use('ggplot')
g = sns.FacetGrid(tips, col="smoker", size=5, aspect=1.5)
g.map(sns.boxplot, "sex", "total_bill", palette='viridis', order=['Male', 'Female'])
plt.show()

现在我想在每个图中画出不同的水平线。例如,一条水平线(坐标为(0,10))仅在左侧绘图中,另一条水平线(坐标为(0,30))仅在右侧绘图中

我该怎么做呢


Tags: theimport绘图plot方式loadpltseaborn
3条回答

可以使用FacetGrid.axes获取FacetGrid中使用的轴的列表,该列表返回使用的轴。然后,可以使用这些轴执行所有常规matplotlib操作,例如^{}用于水平线,或者^{}用于在轴上放置文本:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")

# Plot using Facegrid, separated by smoke
plt.style.use('ggplot')
g = sns.FacetGrid(tips, col="smoker", size=5, aspect=1.5)
g.map(sns.boxplot, "sex", "total_bill", palette='viridis', order=['Male', 'Female'])

ax1, ax2 = g.axes[0]

ax1.axhline(10, ls='--')
ax2.axhline(30, ls='--')

ax1.text(0.5,25, "Some text")
ax2.text(0.5,25, "Some text")

plt.show()

enter image description here

此外,如果您有一组栅格,希望在所有栅格中添加一条水平线(例如y=10),则可以使用栅格对象“映射”“plt.axhline”:

import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# Plot using Facegrid, separated by smoke
plt.style.use('ggplot')
g = sns.FacetGrid(tips, col="smoker", size=5, aspect=1.5)
g.map(sns.boxplot, "sex", "total_bill", palette='viridis', order=['Male', 'Female'])

g.map(plt.axhline, y=10, ls='--', c='red')

axhlinehlines。简单的例子:

chart = sns.relplot(x="x", y="y", kind="line", data=df)

chart.axes[0][0].axhline(y = 10, color='black', linewidth=2, alpha=.7)
chart.axes[0][0].hlines( y = 20, color='black', linewidth=2, alpha=.7, 
                         xmin = 30, xmax = 50) 

似乎hlines允许minmax(documentation),但axhline不允许

相关问题 更多 >