R语言 ggplot2绘制多线图或时间序列图

R语言 ggplot2绘制多线图或时间序列图

在这篇文章中,我们将讨论如何用R编程语言中的ggplot2包绘制多线图或时间序列图。我们可以使用ggplot2包的geom_line()函数来创建一个线图。

语法

ggplot( df, aes( x, y ) )+ geom_line()

其中。

  • df: 决定了所使用的数据框架
  • x和y: 决定了轴上的变量

例子

这里,是一个使用ggplot2包的geom_line()函数绘制的基本线图。这里,使用的数据集是1975年到2015年的城市犯罪数据集,可以从ucr_crime.com下载。

# load package tidyverse
library(tidyverse) 
  
# read sample data from given csv file
sample_data <- read_csv("ucr_crime_1975_2015.csv")
  
# plot a basic line plot using ggplot() function
# color parameter is used to colot the plot according 
# to department_name
ggplot(sample_data, aes(x=year, violent_per_100k)) +
  
# geom_line function is used to plot line plot
geom_line()
R

输出

用R语言中的ggplot2绘制多线图或时间序列图

在这里,结果图看起来不像是多个时间序列。这是因为在上面的例子中,对于多个时间序列,我们只用了两个变量,而这两个变量需要用于绘制单个时间序列图。为了得到一个多重时间序列图,我们需要多一个差异化的变量。因此,我们将使用颜色参数,根据另一个区分口径的变量对线图进行分组和着色。

语法

ggplot( df, aes( x, y, color )+ geom_line()

其中

  • df: 决定了所使用的数据框架
  • x和y: 决定了轴上的变量
  • color: 决定变量,根据该变量对图进行分组和着色。

例子

这里,是一个使用ggplot2包的geom_line()函数绘制的基本线图。在这里,我们根据部门名称对该图进行分组和着色。这为多个时间序列创造了必要的三个差异化变量。

# load package tidyverse
library(tidyverse) 
  
# read sample data from given csv file
sample_data <- read_csv("ucr_crime_1975_2015.csv")
  
# plot a basic line plot using ggplot() function
# color parameter is used to colot the plot according
# to department_name
ggplot(sample_data, aes(x=year, violent_per_100k, color=department_name)) +
  
# geom_line function is used to plot line plot
geom_line()+
  
# theme with legend.position as none removes the 
# legend form plot
theme(legend.position = "none")
R

输出

用R语言中的ggplot2绘制多线图或时间序列图

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册