R语言 绘制X轴上有日期标签的时间序列图

R语言 绘制X轴上有日期标签的时间序列图

在这篇文章中,我们将讨论如何在R语言的X轴上绘制带有日期标签的时间序列的支持性例子。

方法1:使用plot()方法

基础R语言中的plot()方法是一个通用的绘图函数。它分别绘制了x轴和y轴的相应坐标。绘图可以自定义,以便在绘图中添加线型和线宽。

语法

plot(x, y, …)

参数:

x, y – 要绘制的坐标。

输入的数据框包含col1作为日期字符串,col2作为相应的时间戳。

例子

# defining a data frame
data_frame <- data.frame( col1 = c("6/7/2021","7/7/2021","8/7/2021",
                                   "9/7/2021","10/7/2021"),
                          col2 = c(799355, 805800,701262,531579,
                                   690068)
)
  
print ("Original Dataframe")
print (data_frame)
  
# describing new column in date class
data_framecol3 <- as.Date(data_framecol1, "%m/%d/%Y",)
  
# plotting the data
plot(data_framecol3, data_framecol2 , 
     cex = 0.9,type = "l" ,xaxt = "n"  )
  
# Add dates to x-axis
axis(1,                                                   
     data_framecol3,
     format(data_framecol3, "%d-%m-%Y"))
R

输出

[1] "Original Dataframe"
col1   col2
1  6/7/2021 799355
2  7/7/2021 805800
3  8/7/2021 701262 
4  9/7/2021 531579 
5 10/7/2021 690068
R

在R语言中绘制X轴上有日期标签的时间序列图

方法2:使用ggplot()方法

ggplot2库用于在R编程语言工作空间窗口中显示描述性的复杂图。

ggplot()方法用于绘制指定数据框的数据点,并指定一组绘图美学。它用于创建一个美学映射,并添加一个特定的geom函数映射。

语法

ggplot(data = NULL, mapping = aes(c1, c2 ))+ geom_line()

参数:

data – 要绘制的默认数据集

mapping – 要使用的美学映射。

geom_line()用于以线和点的形式添加几何图形。它用于绘制时间序列以及绘图中的线条。

例子

library("ggplot2")
  
# defining a data frame
data_frame <- data.frame( col1 = c("1/6/2021","1/7/2021","1/8/2021",
                                   "1/9/2021","1/10/2021"),
                          col2 = c(799355, 805800,701262,531579,
                                   690068)
)
  
print ("Original Dataframe")
print (data_frame)
  
# describing new column in date class
data_framecol3 <- as.Date(data_framecol1, "%m/%d/%Y")
  
# plotting the data
ggplot( data = data_frame, aes( col3, col2 )) + geom_line() +
scale_x_date(date_labels = "%Y-%m-%d")
R

输出

[1] "Original Dataframe"
col1   col2
1  6/7/2021 799355
2  7/7/2021 805800
3  8/7/2021 701262
4  9/7/2021 531579
5 10/7/2021 690068
R

在R语言中绘制X轴上有日期标签的时间序列图

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册