R语言训练

R画scatterplot及代码

2019-10-26  本文已影响0人  gtt儿_生物信息学习

微信公众号:生物信息学习

在数据分析中经常会需要画各种图,其中比较常见的图之一就是scatterplot,那用R如何画好看的scatterplot呢?可以用geom_point来画图,用geom_smooth添加曲线,简单的例子如下:

options(scipen=999)  # turn-off scientific notation like 1e+48
library(ggplot2)
theme_set(theme_bw())  # pre-set the bw theme.
data("midwest", package = "ggplot2")

gg <- ggplot(midwest, aes(x=area, y=poptotal)) + 
  geom_point(aes(col=state, size=popdensity)) + 
  geom_smooth(method="loess", se=F) + 
  xlim(c(0, 0.1)) + 
  ylim(c(0, 500000)) + 
  labs(subtitle="Area Vs Population", 
y="Population", 
x="Area", 
       title="Scatterplot", 
       caption = "Source: midwest")

plot(gg)
image.png

那如果我们想把一些点圈出来如何做呢?我们可以用geom_encircle来圈,具体例子如下所示:

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即可得代码。

上一篇下一篇

猜你喜欢

热点阅读