如何使用R绘制散点图和直方图

时间:2012-10-28 08:49:48

标签: r

我有一个关于最大风速(cm)的数据集如下:

Year Jan Feb Mar Apr May June July Aug Sept Oct Nov Dec     
2011 4.5 5.6 5.0 5.4 5.0 5.0  5.2  5.3 4.8  5.4 5.4 3.8     
2010 4.6 5.0 5.8 5.0 5.2 4.5  4.4  4.3 4.9  5.2 5.2 4.6     
2009 4.5 5.3 4.3 3.9 4.7 5.0  4.8  4.7 4.9  5.6 4.9 4.1     
2008 3.8 1.9 5.6 4.7 4.7 4.3  5.9  4.9 4.9  5.6 5.2 4.4     
2007 4.6 4.6 4.6 5.6 4.2 3.6  2.5  2.5 2.5  3.3 5.6 1.5     
2006 4.3 4.8 5.0 5.2 4.7 4.6  3.2  3.4 3.6  3.9 5.9 4.4     
2005 2.7 4.3 5.7 4.7 4.6 5.0  5.6  5.0 4.9  5.9 5.6 1.8     

如何使用R编程创建月最大风速散点图(x轴月和y轴风速)以及月最大风速直方图?

1 个答案:

答案 0 :(得分:2)

我建议阅读R的介绍,但这应该让你开始。

df <- read.table(text="Year Jan Feb Mar Apr May June July Aug Sept Oct Nov Dec     
2011 4.5 5.6 5.0 5.4 5.0 5.0  5.2  5.3 4.8  5.4 5.4 3.8     
2010 4.6 5.0 5.8 5.0 5.2 4.5  4.4  4.3 4.9  5.2 5.2 4.6     
2009 4.5 5.3 4.3 3.9 4.7 5.0  4.8  4.7 4.9  5.6 4.9 4.1     
2008 3.8 1.9 5.6 4.7 4.7 4.3  5.9  4.9 4.9  5.6 5.2 4.4     
2007 4.6 4.6 4.6 5.6 4.2 3.6  2.5  2.5 2.5  3.3 5.6 1.5     
2006 4.3 4.8 5.0 5.2 4.7 4.6  3.2  3.4 3.6  3.9 5.9 4.4     
2005 2.7 4.3 5.7 4.7 4.6 5.0  5.6  5.0 4.9  5.9 5.6 1.8",header=TRUE)
#look at ?read.csv to learn how to read your data from a CSV file

#transform data.frame into long format
library(reshape2)
df <- melt(df,id="Year",variable.name = "Month",value.name = "Speed")

#plot boxplots per month
plot(Speed~Month,data=df)

boxplot

#histogram for January
hist(df$Speed[df$Month=="Jan"],main="Max wind speed in January",xlab="Speed")

histogram Jan

#histogram for 2011
hist(df$Speed[df$Year==2011],main="Max wind speed in 2011",xlab="Speed")

histogram 2011

#create actual dates
df$Month2 <- factor(df$Month)
levels(df$Month2) <- 1:12
df <- transform(df,Time = as.Date(paste(Year,Month2,"15",sep="-"),'%Y-%m-%d'))
#plot Speed vs Time
plot(Speed~Time,data=df[order(df$Time),],type="l")

time series