How to add a comparison line to all plots when using Seaborn's FacetGrid

旧时模样 提交于 2020-05-17 08:15:07

问题


I'm trying to add the same comparison line to multiple plots using FacetGrid. Here is where I get stuck:

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

# Plot using FaceGrid, separated by smoke
g = sns.FacetGrid(tips, col="smoker", size=5, aspect=1.5)
g.map(plt.scatter, "tip", "total_bill")
x = np.arange(0, 50, .5)
y = 0.2*x
plt.plot(y, x, C='k')
plt.show()

Here are the results

As you can see, the line shows up on the last plot, but not the first. How do I get it on both?


回答1:


You can map the same function to the FacetGrid.

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

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

# Plot using FaceGrid, separated by smoke
g = sns.FacetGrid(tips, col="smoker", height=5, aspect=1.5)
g.map(plt.scatter, "tip", "total_bill")

def const_line(*args, **kwargs):
    x = np.arange(0, 50, .5)
    y = 0.2*x
    plt.plot(y, x, C='k')

g.map(const_line)

plt.show()



回答2:


Another indirect way is to get the axes object from the FacetGrid and then plot the line to each of them

g = sns.FacetGrid(tips, col="smoker", size=5, aspect=1.5)
g.map(plt.scatter, "tip", "total_bill")

axes = g.fig.axes
x = np.arange(0, 50, .5)
y = 0.2*x
for ax in axes:
    ax.plot(y, x, C='k')
plt.show()



来源:https://stackoverflow.com/questions/54390054/how-to-add-a-comparison-line-to-all-plots-when-using-seaborns-facetgrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!