【问题标题】:Plotting multiple smooth lines from a dataframe从数据框中绘制多条平滑线
【发布时间】:2012-06-16 09:45:08
【问题描述】:

我对 R 比较陌生。我正在尝试绘制从 csv 文件加载的数据框。数据由 6 列组成,如下所示:

xval,col1,col2,col3,col4,col5

第一列 (xval) 由一系列单调递增的正整数(例如 10、40、60 等)组成,其他列 1 到 5 列由浮点数组成。

我想在 R 中创建如下图:

  • 在 x 轴上绘制 xval 项
  • 绘制剩余的列 (col1 ... col5) 行
  • 用 col2 创建一个图例图例,... col5 重命名

要绘制的数据 (col1, ... col5) 是“快照”值,因此虽然我想将它们绘制为线条,但我希望线条被平滑(即插值)。

我正在寻找一个 sn-p,它可以在我将数据读入数据框后帮助我创建绘图。任何帮助将不胜感激。

【问题讨论】:

    标签: r graph plot


    【解决方案1】:

    看看ggplot2

    #create dummy data
    n <- 200
    dataset <- data.frame(xval = runif(n), col1 = rnorm(n), col2 = rnorm(n, sd = 2), col3 = rnorm(n, mean = seq(0, 2, length = n)), col4 = rnorm(n, sd = seq(0, 1, length = n)), col5 = rnorm(n, mean = 1))
    #convert data to long format
    library(reshape)
    Molten <- melt(dataset, id.vars = "xval")
    #plot it
    library(ggplot2)
    ggplot(Molten, aes(x = xval, y = value, colour = variable)) + 
        geom_smooth() + geom_point()
    #some tweaking
    ggplot(Molten, aes(x = xval, y = value, colour = variable)) + 
        geom_smooth(se = FALSE) + geom_point() + theme_bw() + 
        scale_x_continuous("the x label") + scale_x_continuous("the y label") +
        scale_colour_discrete("")
    

    【讨论】:

    • +1 简洁漂亮的代码!。谢谢!。我不敢相信你能用这么几行代码做到这一点! :)。我需要稍微修改图表以使其成为我想要的样子。我已设法删除“散点”,但我需要:1. 删除绘制线周围的“置信带(?)”2. 重命名 x和 Y 轴 3. 删除图例标题 3. 为绘图使用白色背景。
    • 顺便说一句,(如果我错了,请纠正我),我是 R 的新手,似乎现在大多数与 R 图形相关的问题的答案都涉及到 ggplot(2) 的解决方案 - 应该我专注于学习如何使用 ggplot2 而不是 R 自己的 plot() 命令?
    • 如果有为一个调整的情节添加一行代码。查看 ggplot2 网站 (had.co.nz/ggplot2) 获取代码示例。了解 plot() 命令的基础知识很好,但使用 ggplot() 生成高质量的绘图要容易得多。使用 plot() 命令生成相同的绘图需要几行代码。
    • 我肯定会专注于 ggplot2。在我看来优于标准plot和lattice。
    • scale_x_continuous("the y label") 应该是scale_y_continuous("the y label")
    猜你喜欢
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2011-12-16
    • 2014-06-18
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    相关资源
    最近更新 更多