R绘制散点图

R绘制散点图

参考资料:

《R语言数据分析与可视化从入门到精通》
《R数据可视化手册》

基本散点图

直接使用R基础包的绘图函数plot()

plot(mtcars$wt, mtcars$mpg)

在这里插入图片描述

或使用ggplot2中的qplot()函数:

library(ggplot2)
qplot(mtcars$wt, mtcars$mpg)

在这里插入图片描述

如果绘图所用的两个参数向量包含在同一个数据框内,则可以运行下面的命令:

library(ggplot2)
qplot(wt,mpg,data=mtcars)
# 或者
ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point()

在这里插入图片描述

使用gcookbook中的数据集heightweight中的两列:ageYearheightIn

library(gcookbook) # 为了使用数据
# 列出我们用到的列
head(heightweight[, c("ageYear", "heightIn")])

运行结果如下:

  ageYear heightIn
1   11.92     56.3
2   12.92     62.3
3   12.75     63.3
4   13.42     59.0
5   15.92     62.5
6   14.25     62.5

画图:

library(gcookbook) # 为了使用数据
library(ggplot2)
ggplot(heightweight, aes(x=ageYear, y=heightIn)) +
  geom_point()

在这里插入图片描述

设置点形和颜色

以上代码绘制了ggplot2的基本散点图。在绘图时,ggplot2会自动生成一些默认风格,不过这些风格都可以重新设置,也可以将其括号内的参数直接写进geom_point()中。

geom_point()函数中的shape参数、col参数和fill参数改变点的形状和颜色

library(gcookbook) # 为了使用数据
library(ggplot2)
ggplot(heightweight, aes(x=ageYear, y=heightIn)) +
  geom_point(shape=2, col="red")

在这里插入图片描述

shape2时,点的颜色只能由col控制;但对于其他一些类型的点,如shape23时,也可使用fill参数指定填充颜色:

library(ggplot2)
ggplot(mtcars, aes(x=wt, y=mpg)) +
  geom_point(shape=23, col="green", fill="purple")

在这里插入图片描述

基于某变量对数据进行分组设置点形和颜色

同样,使用gcookbook中的heightweight数据集的sexageYearheightIn三列

library(gcookbook) # 为了使用数据
# 列出要用的三个列
head(heightweight[, c("sex", "ageYear", "heightIn")])
  sex ageYear heightIn
1   f   11.92     56.3
2   f   12.92     62.3
3   f   12.75     63.3
4   f   13.42     59.0
5   f   15.92     62.5
6   f   14.25     62.5
library(gcookbook) # 为了使用数据
library(ggplot2)
ggplot(heightweight, aes(x=ageYear, y=heightIn, shape=sex, colour=sex)) +
  geom_point()

在这里插入图片描述

通过调用scale_shape_manual()函数可以使用其他点形;调用scale_colour_brewer()或者scale_colour_manual()函数可以使用其他调色板。

library(gcookbook) # 为了使用数据
library(ggplot2)
ggplot(heightweight, aes(x=ageYear, y=heightIn, shape=sex, colour=sex)) +
  geom_point() +
  scale_shape_manual(values=c(1,2)) +
  scale_colour_brewer(palette="Set1")

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值