0
点赞
收藏
分享

微信扫一扫

R绘制折线图

mjjackey 2022-02-01 阅读 164

R绘制折线图

基本图形

R基础函数

使用plot()函数绘制折线图时需向其传递一个包含x值的向量和一
个包含y值的向量,并使用参数type="l"

plot(pressure$temperature, pressure$pressure, type="l")

在这里插入图片描述

若要向图形中添加数据点或者多条折线,则需先用plot()函数绘制第一条折线,再通过points()函数和lines()函数分别添加数据点和更多折线:

plot(pressure$temperature, pressure$pressure, type="l")
points(pressure$temperature,pressure$pressure)
lines(pressure$temperature, pressure$pressure/2, col="red")
points(pressure$temperature, pressure$pressure/2, col="red")

在这里插入图片描述

ggplot2绘图系统

library(ggplot2)
ggplot(pressure, aes(x=temperature, y=pressure)) +
  geom_line()

添加数据标记

在代码中加入geom_point(),如下:

library(ggplot2)
ggplot(pressure, aes(x=temperature, y=pressure)) +
  geom_line() +
  geom_point()

运行结果:

在这里插入图片描述

可以在geom_point()函数中,指定sizeshape参数调整点的大小和形状。

library(ggplot2)
ggplot(pressure, aes(x=temperature, y=pressure)) +
  geom_line() +
  geom_point(size=4, shape=21, fill="purple")

在这里插入图片描述

多重折线图

在分别设定一个映射给xy的基础上,再将另外一个(离散型)变量映射给颜色
(colour)或者线型(linetype)即可。

library(ggplot2)
library(dplyr)
data <- mtcars %>% 
  group_by(am, cyl) %>% 
  summarize_at(.vars = "mpg", .funs = mean) %>% 
  ungroup() %>% 
  mutate(am = as.character(am)) 

# 将am映射给线型
ggplot(data, aes(x = cyl,y = mpg, linetype = am )) + 
  geom_line()

# 将am映射给线条颜色
ggplot(data, aes(x = cyl,y = mpg, color = am )) + 
  geom_line()

在这里插入图片描述

在这里插入图片描述

library(dplyr)
data <- mtcars %>% 
  group_by(am, cyl) %>% 
  summarize_at(.vars = "mpg", .funs = mean) %>% 
  ungroup() %>% 
  mutate(am = as.character(am)) 

# 使用数据标记
ggplot(data, aes(x = cyl,y = mpg, fill = am )) + 
  geom_line() +
  geom_point(size=4, shape=21)  # 使用有填充色的点

# 手动设置填充色
ggplot(data, aes(x = cyl,y = mpg, fill = am )) + 
  geom_line() +
  geom_point(size=4, shape=21) +  # 使用有填充色的点
  scale_fill_manual(values=c("black","white"))

在这里插入图片描述

在这里插入图片描述

修改线条样式

通过设置线型(linetype)、线宽(size)和颜色(colour)参数可以分别修改折线
的线型、线宽和颜色。如下:

library(ggplot2)
ggplot(pressure, aes(x=temperature, y=pressure)) +
  geom_line(linetype="dashed", size=1, colour="blue")

在这里插入图片描述

举报

相关推荐

0 条评论