# Super simple confidence interval fitting scatter plot drawing method recommended~~

Today's tweet is to write some basic content: how to plot the fitting results of the linear model and its confidence interval on a scatter plot. Here the editor uses R and Python to draw separately, the main content is as follows:

• R-ggplot2::geom_smooth() function to draw
• Python-seaborn::lmplot() function to draw

## R-ggplot2::geom_smooth() function to draw

The editor will add the necessary chart elements in combination with the R-ggpubr package. First, we use ggplot2 for basic drawing, as follows:

"Example 1": a single category

```library(tidyverse)
library(ggtext)
library(hrbrthemes)
library(wesanderson)
library(LaCroixColoR)
library(RColorBrewer)
library(ggsci)
# Visual drawing
ggplot(data = test_df,aes(x = total_bill,y = tip)) +
geom_point(shape=21,fill="#0073C2",colour="black",size=3,stroke=.5) +
geom_smooth(fill="#868686",colour="#CD534C") +
labs(
title = "Example of <span style='color:#D20F26'>ggplot2::geom_smooth function</span>",
subtitle = "processed charts with <span style='color:#1A73E8'>geom_smooth(method = 'loess')</span>",
caption = "Visualization by <span style='color:#0057FF'>DataCharm</span>") +
hrbrthemes::theme_ipsum(base_family = "Roboto Condensed")  +
theme(
plot.title = element_markdown(hjust = 0.5,vjust = .5,color = "black",
size = 20, margin = margin(t = 1, b = 12)),
plot.subtitle = element_markdown(hjust = 0,vjust = .5,size=15),
plot.caption = element_markdown(face = 'bold',size = 12))
```
copy

Example of ggplot2::geom_smooth(method = 'loess')

Note: The method = 'loess' parameter setting is used here, and method = 'l' can also be set. The result (here we also set the ggpubr package to add some drawing elements):

```ggplot(data = test_df,aes(x = total_bill,y = tip)) +
geom_point(shape=21,fill="#0073C2",colour="black",size=3,stroke=.5) +
geom_smooth(method = lm,fill="#868686",colour="#CD534C") +
ggpubr::stat_regline_equation(label.x = .1,label.y = 10,size=6,fontface='bold') +
ggpubr::stat_cor(aes(label = paste(..r.label..,..p.label.., sep = "~`,`~")),
label.x = .1, label.y = 9,size=6,fontface='bold') +
labs(x="",y="",
title = "Example of <span style='color:#D20F26'>ggplot2::geom_smooth function</span>",
subtitle = "processed charts with <span style='color:#1A73E8'>geom_smooth(method = 'lm')</span>",
caption = "Visualization by <span style='color:#0057FF'>DataCharm</span>") +
hrbrthemes::theme_ipsum(base_family = "Roboto Condensed")  +
theme(
plot.title = element_markdown(hjust = 0.5,vjust = .5,color = "black",
size = 20, margin = margin(t = 1, b = 12)),
plot.subtitle = element_markdown(hjust = 0,vjust = .5,size=15),
plot.caption = element_markdown(face = 'bold',size = 12))
```
copy

Example of ggplot2::geom_smooth(method = 'lm')

It can be seen that: using ggpubr::stat_regline_equation() and ggpubr::stat_cor() add the fitting formula and the addition of indicators such as R and P, respectively. Next, the editor will introduce how to draw multiple elements.

"Example 2": Multiple Categories

To draw a chart of multiple categories, you only need to set the mapping, as follows:

```ggplot(data = test_df,aes(x = total_bill,y = tip)) +
geom_point(aes(fill=sex),shape=21,size=3,stroke=.5) +
geom_smooth(aes(colour=sex,fill=sex),method = lm) +
ggsci::scale_fill_nejm()+
ggsci::scale_colour_nejm()+
ggpubr::stat_regline_equation(aes(color=sex),label.x = .1,size=6,fontface='bold') +
ggpubr::stat_cor(aes(label = paste(..r.label..,..p.label.., sep = "~`,`~"),color=sex),
label.x = 20,size=6,fontface='bold') +
labs(x="",y="",
title = "Example of <span style='color:#D20F26'>ggplot2::geom_smooth function</span>",
subtitle = "processed charts with <span style='color:#1A73E8'>geom_smooth(method = 'lm')</span>",
caption = "Visualization by <span style='color:#0057FF'>DataCharm</span>") +
hrbrthemes::theme_ipsum(base_family = "Roboto Condensed")  +
theme(
plot.title = element_markdown(hjust = 0.5,vjust = .5,color = "black",
size = 20, margin = margin(t = 1, b = 12)),
plot.subtitle = element_markdown(hjust = 0,vjust = .5,size=15),
plot.caption = element_markdown(face = 'bold',size = 12))
```
copy

Example03 of ggplot2::geom_smooth(method = 'lm'

Of course, set geom_smooth(method = 'loess') to get the following visualization:

Example04 of ggplot2::geom_smooth(method = 'loess'

The above briefly introduces the method of drawing in R. Next, we introduce the use of Python to draw such graphs.

## Python-seaborn::lmplot() function to draw

Here the editor uses the lmplot() function in the Python-seaborn library to draw, as follows:

"Example 1": a single category

```import seaborn as sns
import matplotlib.pyplot as plt
# Visualize global settings
plt.style.use('fivethirtyeight')
plt.rcParams['font.family'] = "Times New Roman"
plt.rcParams["axes.titlesize"] = 18
#Visual drawing
sns.lmplot(x="total_bill", y="tip", data=tips,height=5, aspect=1.2,scatter_kws={"color":"#0073C2","edgecolor":"black"},
line_kws={"color":"#BC3C28","linewidth":2})

# Since the ax parameter is not supported, we can do this
ax = plt.gca()
# Customized operation
ax.set_facecolor("white")
for spine in ['top','bottom','left','right']:
ax.spines[spine].set_color("white")
ax.tick_params(labelsize = 15,direction = 'in')
#ax.grid(which='major',axis='y',ls='--',c='k',alpha=.7)
ax.grid(which='major',ls='--',c='k',alpha=.7)
ax.set_xlim(left=0,right=55)
ax.set_ylim(bottom=0,top=10.5)

titlefontdict = {"size":23,"color":"k",'family':'Times New Roman'}
ax.set_title('Example01 Of Linear Regression Scatter Plot ',titlefontdict,pad=15)
text_font = {'family':'Times New Roman','size':'22','weight':'bold','color':'black'}
ax.text(.9,.9,"(a)",transform = ax.transAxes,fontdict=text_font,zorder=4)
ax.text(.8,.056,'\nVisualization by DataCharm',transform = ax.transAxes,
ha='center', va='center',fontsize = 11,color='black')
```
copy

Example01 Of seaborn.lmplot()

Note: Since seaborn.lmplot() does not support the ax attribute setting, if we want to customize it, we can do it with the following statement:

```ax = plt.gca()
```
copy

By setting this statement, we can use some commonly used matplotlib custom operation statements~

"Example 2": Multiple categories The seaborn.lmplot() function is also very simple to draw multiple categories of charts, just by setting the hue parameter, the details are as follows:

```sns.lmplot(x="total_bill", y="tip", hue="sex",hue_order=['Female','Male'],data=tips,height=5, aspect=1.2,
palette=["#BC3C28","#0072B5"],scatter_kws={"edgecolor":"black"},line_kws={"linewidth":2})

# Since the ax parameter is not supported, we can do this
ax = plt.gca()
# Customized operation
ax.set_facecolor("white")
for spine in ['top','bottom','left','right']:
ax.spines[spine].set_color("white")
ax.tick_params(labelsize = 15,direction = 'in')
#ax.grid(which='major',axis='y',ls='--',c='k',alpha=.7)
ax.grid(which='major',ls='--',c='k',alpha=.7)
ax.set_xlim(left=0,right=55)
ax.set_ylim(bottom=0,top=10.5)

titlefontdict = {"size":23,"color":"k",'family':'Times New Roman'}
ax.set_title('Example02 Of Linear Regression Scatter Plot ',titlefontdict,pad=15)
text_font = {'family':'Times New Roman','size':'22','weight':'bold','color':'black'}
ax.text(.9,.9,"(a)",transform = ax.transAxes,fontdict=text_font,zorder=4)
ax.text(.8,.056,'\nVisualization by DataCharm',transform = ax.transAxes,
ha='center', va='center',fontsize = 11,color='black')
```
copy

Example02 Of seaborn.lmplot()

It can be seen from this that Python-seaborn and ggplot2 have similar drawing syntax, and are more friendly to some statistical drawings. If you need to draw customized charts, you need to be familiar with the meaning of each attribute function of matplotlib.

The above is a brief introduction to how to use R and Python to draw scatter plots with fitted intervals. For more details, please refer to: ggplot2::geom_smooth()[1]seaborn.lmplot()[2]

## Summarize

The editor of this tweet briefly introduces how to draw the fitting results of the linear model and its confidence interval on the scatter plot, and also compares the differences between R-ggplot2 and Python-seaborn. I hope my friends They can choose their own tools to draw visual charts.

### References

[1]

ggplot2::geom_smooth() info: https://ggplot2.tidyverse.org/reference/geom_smooth.html.

[2]

seaborn.lmplot() data: https://seaborn.pydata.org/generated/seaborn.lmplot.html#seaborn.lmplot.

Tags: Python

Posted by newbiez on Tue, 25 Oct 2022 11:13:33 +1030