Alex Ash
Alex Ash

Reputation: 41

Show confidence interval in legend of plot in Python / Seaborn

I am generating some scatter plots with linear regression and confidence interval using seaborn on Python, with the sns.regplot function. I could find a way to show the Regression line in the legend, but I would also like to add the Confidence Interval in the legend (with the transparent blue as the reference colour).

Here is the code I have and the result I get so far.

Tobin_Nationality_Reg = sns.regplot(x="Nationality_Index_Normalized",
                        y="Tobins_Q_2017",
                        data=Scatter_Plot,
                        line_kws={'label':'Regression line'})

plt.xlabel("Nationality Index")
plt.ylabel("Tobin's Q")
plt.legend()`
plt.savefig('Tobin_Nationality_Reg.png')

Here is the output I currently get: Scatter Plot

enter image description here

Does anybody have an idea how I could do that? Thanks in advance.

Upvotes: 4

Views: 2864

Answers (1)

gmds
gmds

Reputation: 19885

I believe there is no clean way to do this, because seaborn does not expose keyword arguments for the fill_between call that plots the confidence interval.

However, it can be done by modifying the label attribute of the PolyCollection directly:

x, y = np.random.rand(2, 20)

ax = sns.regplot(x, y, line_kws={'label': 'Regression line'})
ax.collections[1].set_label('Confidence interval')
ax.legend()

enter image description here

Upvotes: 5

Related Questions