美文网首页R可视化和ggplot2
《R数据可视化手册》学习笔记2---快速探索数据(2)折线图

《R数据可视化手册》学习笔记2---快速探索数据(2)折线图

作者: RSP小白之路 | 来源:发表于2023-09-05 08:41 被阅读0次

    写在前面。

    很多时候在处理数据前或者出图前,可能需要先对数据整体情况进行了解。这个时候我们可以用到R基础绘图的语句ggplot2完成目标。

    接下来,我们分不同的图形类型进行啃书学习。


    2. 绘制折线图

    如何绘制折线图?

    使用R内置数据集pressure作为示例数据。

    > str(pressure)
    'data.frame':   19 obs. of  2 variables:
     $ temperature: num  0 20 40 60 80 100 120 140 160 180 ...
     $ pressure   : num  0.0002 0.0012 0.006 0.03 0.09 0.27 0.75 1.85 4.2 8.8 ...
    
    • 使用R基础绘图系统

    使用plot()函数,同时添加参数type="l"

    plot(pressure$temperature, pressure$pressure, type = "l")
    
    基础绘图系统绘制的散点图

    如果我们要给线上加上散点,同时再绘制一条红色折线并加上红色的散点,则使用如下语句,其中,dev.off()清除绘图板上已有的图像。

    dev.off()
    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")
    
    基础绘图系统绘制的折线散点图

    如果用图层思想理解,相当于plot建立了一个图层并绘制了一条折线,pointslines在图层之上又添加图层和元素。

    • 使用ggplot2qplot函数

    通过在qplot函数中添加选项geom='line'指定绘制图形的几何学类型,geom就是几何学geometry的缩写。

    qplot(pressure$temperature, pressure$pressure, geom = "line")
    
    qplot函数绘制的折线图

    如果要给线上加上散点,则添加参数geom = c("line" ,"point")

    qplot(pressure$temperature, pressure$pressure, geom = c("line" ,"point")) 
    
    qplot函数绘制的折线散点图

    上述语句等价于我们在使用ggplo2绘图时更常用的语句形式:

    ggplot(data = pressure, aes(temperature, pressure)) + geom_line() + geom_point()
    

    以上。

    相关文章

      网友评论

        本文标题:《R数据可视化手册》学习笔记2---快速探索数据(2)折线图

        本文链接:https://www.haomeiwen.com/subject/velbmdtx.html