R绘制折线图
参考资料:
《R语言数据分析与可视化从入门到精通》
《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()
函数中,指定 size
或 shape
参数调整点的大小和形状。
library(ggplot2)
ggplot(pressure, aes(x=temperature, y=pressure)) +
geom_line() +
geom_point(size=4, shape=21, fill="purple")
多重折线图
在分别设定一个映射给 x
和 y
的基础上,再将另外一个(离散型)变量映射给颜色
(colour)或者线型(linetype)即可。
library(ggplot2)
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, linetype = am )) +
geom_line()
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")
Original: https://blog.csdn.net/github_62245663/article/details/122763122
Author: PASSER-BY007
Title: R绘制折线图
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/692851/
转载文章受原作者版权保护。转载请注明原作者出处!