在 R 中绘制折线图

Plotting line graph in R

我想将 these data 绘制成一个简单的 scatterplot/line 图表,以显示 CO2 水平的线性变化。但是,我无法绘制它,因为我无法将矩阵向量化为适当的向量。谁能帮我找到正确的方法?

感谢您的宝贵时间

此解决方案需要 development version of data.table v1.9.5

data.table 包中的

fread 在读取数据方面做得很好,同时省略了不需要的文本行。然后,您可以使用 melt 重塑数据,也可以使用 data.table,准备绘制。

# libraries
library(data.table)
library(ggplot2)

# read in data
dat <- fread("http://cdiac.ornl.gov/ftp/trends/co2/barrsio.co2", data.table=F)

# remove spaces in names
setnames(dat, names(dat), make.names(names(dat)))

# reshape data
dat_m <- melt(dat[-ncol(dat)], id.vars="V1")

# plot
ggplot(dat_m, aes(variable, value, group=1)) +
       geom_point() +
       geom_line() +
       facet_wrap(~ V1, nrow=6)

生产

或者如果你想绘制每年的平均值

ggplot(dat, aes(V1, Ann..Ave.)) +
       geom_point() +
       geom_line() +
       scale_x_continuous(breaks=seq(1974, 2007, 5))

给予

使用基本 R 函数

作为仅使用基本 R 函数的替代视角

 ### Download the file
    download.file("http://cdiac.ornl.gov/ftp/trends/co2/barrsio.co2", 
                  "~/Downloads/so-data.txt")
    ### Read the data line by line
    raw.dat <- readLines(file("~/Downloads/so-data.txt"))
    ### Extract the column names
    col.names.index <- grep("jan.*feb", raw.dat, ignore.case=TRUE)
    col.names <- raw.dat[col.names.index]
    col.names <- strsplit(col.names, split='\t')[[1]]
    (col.names <- col.names[-1])
    ### Extract the row names
    row.names.index <- grep('^[12][019][0-9][0-9]', raw.dat)
    row.names <- raw.dat[row.names.index]
    row.names <- substr(row.names, 1, 4)
    ### Extract the data
    data.rows.index <- row.names.index
    data.rows <- raw.dat[row.names.index]
    ### I had to fix the first row of the data as it was missing a tab
    ### I don't know if this is true in the original file
    data.rows[1] <- paste(data.rows[1],'\t')
    ### convert to a matrix
    data.rows <-
      matrix(as.numeric(unlist(strsplit(data.rows,
                                        split='\t'))),
             byrow=TRUE,
             ncol=14)

    ### drop the first and last columns: rownames, ave.
    data.rows <- data.rows[,-c(1,13)]
    colnames(data.rows) <- col.names[-13]
    rownames(data.rows) <- row.names

    ### Make the plots
    par(mfrow=c(9,4))
    par(mar=c(1,1,1,1))  ### prevents margins too large error
    for (i in rownames(data.rows))
      plot(data.rows[i,], type='l',main=i)

剧情如下:

您可以使用主成分来查找哪个月份的 CO2 变化更大。

这可能是查看基于特定位置的数据的好方法。

将数据加载到 R 后:

PCA = princomp(~Jan+Feb+March+April+May+June+July+Aug+Sept+Oct+Nov+Dec,Data,cor=TRUE)

PCA

loadings(PCA)
plot(PCA)
biplot(PCA)

双标图我们会将您的数据数据归入变化最大的组件中。