原图
image.png
原始代码
# install 'ggalt' pkg
# devtools::install_github("hrbrmstr/ggalt")
options(scipen = 999)
library(ggplot2)
library(ggalt)
midwest_select <- midwest[midwest$poptotal > 350000 &
midwest$poptotal <= 500000 &
midwest$area > 0.01 &
midwest$area < 0.1, ]
# Plot
ggplot(midwest, aes(x=area, y=poptotal)) +
geom_point(aes(col=state, size=popdensity)) + # draw points
geom_smooth(method="loess", se=F) +
xlim(c(0, 0.1)) +
ylim(c(0, 500000)) + # draw smoothing line
geom_encircle(aes(x=area, y=poptotal),
data=midwest_select,
color="red",
size=2,
expand=0.08) + # encircle
labs(subtitle="Area Vs Population",
y="Population",
x="Area",
title="Scatterplot + Encircle",
caption="Source: midwest")
学习后做的图
image.png
scatterplot with encircling 带有圈 得散点图
图表中列出一些特殊的点或区域,以引起人们对那些特殊情况的注意。
这可以使用ggalt包中的geom_enCircle()方便地完成。
# install.packages('ggalt')
library(ggalt)
ls('package:ggalt')
options(scipen = 999)
library(ggplot2)
library(dplyr)
### select subdata of the dataset 'midwest'
midwest_select=midwest%>%
filter(poptotal>350000&
poptotal<=500000&
area>0.01&
area<0.1)
#plot
ggplot(data=midwest,aes(x=area,y=poptotal))+
geom_point(aes(col=state,size=popdensity))+
geom_smooth(method = 'loess',se=F,formula = 'y~x')+
geom_encircle(aes(x=area,y=poptotal),
data = midwest_select,
color="red",
size=2,
expand=0.08)+
labs(x='Area',
y='Population',
title = 'Scatterplot + Encircle',
subtitle = 'Area Vs Population',
caption = 'Source: midwest')+
xlim(c(0,0.1))+ylim(c(0,500000))+
theme_bold()+
theme(plot.caption = element_text(face='bold'))
参考:Top 50 ggplot2 Visualizations - The Master List
其他ggplot2基本语法教程