1

我想制作雪数据的条形图。数据存储在 .csv 文件中,有一个日期列和 12 个位置列,其中 SWE 值是整数。为了创建条形图,数据类型必须是向量或矩阵。所以我的问题是如何将文件(data.frame)转换为矩阵并从中创建分组条形图。X 轴应为“日期”,Y 轴应为“SWE [mm]” 我的 .csv 文件如下所示:

Date     SB1 SB2 SB3 ...
1.1.2013 95  90  91  ...
1.2.2013 87  80  82  ...
1.3.2013 45  30  15  ...
1.4.2013 23  18  3   ...

到目前为止,我尝试过:

setwd("path")
swe = read.csv("name.csv", header=TRUE, sep=";")
swe$new = paste(swe$Date," ")
swe$new = strptime(swe$new, "%d.%m.%Y")
swe2 <- data.matrix(swe)
dimnames(swe2) <- NA
jpeg("swe_sb1.jpg")
barplot(swe2$Date, swe2$SWE_SB1, ..., beside = TRUE)
dev.off()

它给了我错误信息:

> setwd("path")
> swe = read.csv("name.csv", header=TRUE, sep=";")
> swe$new = paste(swe$Date," ")
> swe$new = strptime(swe$new, "%d.%m.%Y")
> swe2 <- data.matrix(swe)
> dimnames(swe2) <- NA
Fehler in dimnames(swe2) <- NA : 'dimnames' muss eine Liste sein
> str(swe2)
num [1:4, 1:38] 2 1 3 4 119 117 87 118 54 35 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:38] "Date" "SWE_SB1" "SH_SB1" "SD_SB1" ...
> jpeg("swe_sb1.jpg")
> barplot(swe2$Date, swe2$SWE_SB1)
Fehler in swe2$Date : $ operator is invalid for atomic vectors
> dev.off()
jpeg:75:swe_all.jpg 
              2 

任何帮助将不胜感激!

4

2 回答 2

2

You're making this way harder than it is. R has great examples for all of it's functions, so ?barplot might have been a better place to start.

Anyways, what you have is a matrix that you want to make a grouped boxplot from. If you have a matrix like the example one you'd see by typing VADeaths:

Rural       Male Rural   Female     Urban Male   Urban Female
50-54       11.7         8.7        15.4         8.4
55-59       18.1         11.7       24.3         13.6
60-64       26.9         20.3       37.0         19.3
65-69       41.0         30.9       54.6         35.1
70-74       66.0         54.3       71.1         50.0

And you wanted to create a boxplot, you simply type barplot(VADeaths,grouped=T) and you end up with simple bar plot

If you want to switch the x and y, all you have to do is barplot(t(VADeaths),grouped=T), and you have:transposed bar plot. So all you have to do is read in your data using read.csv or whatever, transpose it and plot it!

于 2013-07-23T16:23:41.047 回答
0

read.csv()返回一个data.framebarplot()不接受这个类。

在绘图之前使用as.matrix()将您的数据转换为可接受的类: x <-as.matrix(x)

于 2015-06-02T19:25:29.307 回答