As described in the seaborn API the following code will produce a linear regression plot.
import numpy as np, pandas as pd; np.random.seed(0)
import seaborn as sns; sns.set(style="white", color_codes=True)
tips = sns.load_dataset("tips")
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind='reg')
sns.plt.show()
However, with a lot of data points the regression line is not really visible anymore. How can I change its color? I could not find a builtin seaborn command.
In case the line is in the background (i.e. behind the dots), I would also like to ask how to bring it to the front.
By default, the regression line is blue. To change the color we have to use the keyword color inside the geom_smooth( ) function.
Draw a plot of two variables with bivariate and univariate graphs. This function provides a convenient interface to the JointGrid class, with several canned plot kinds.
regplot() : This method is used to plot data and a linear regression model fit. There are a number of mutually exclusive options for estimating the regression model.
lmplot() method is used to draw a scatter plot onto a FacetGrid.
There are a couple approaches, as mwaskom tactfully pointed out. You can pass arguments to the joint plot, but setting color
there affects the whole scatterplot:
import numpy as np, pandas as pd; np.random.seed(0)
import seaborn as sns#; sns.set(style="white", color_codes=True)
tips = sns.load_dataset("tips")
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind='reg',
joint_kws={'color':'green'}) # Scatter and regression all green
Or pass a dictionary of line-plotting keywords through that dictionary of scatterplot keywords. I read seaborn/linearmodels.py
to figure out where to do this, which was entertaining and informative in itself. Dict in dict:
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind='reg',
joint_kws={'line_kws':{'color':'cyan'}}) # Only regression cyan
Or you can access the line after it's been plotted and change it directly. This depends on the regression line being the first line plotted, so could break with seaborn updates. It's also aesthetically/pedagogically different, as you don't recolor the uncertainty spread. It is a good way to get familiar with what the JointGrid
object is and how else you might interact with it. (And maybe there are properties you can't set with the function call arguments, although I can't think of any.)
g = sns.jointplot(x="total_bill", y="tip", data=tips, kind='reg')
regline = g.ax_joint.get_lines()[0]
regline.set_color('red')
regline.set_zorder(5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With