分组数据,按组查找结果,使用R绘图

时间:2011-03-01 22:13:36

标签: r

预安装的地震数据集有5个变量和1000个观测值。

我想要创建的简单图表应该按地震深度类别显示平均地震震级(即Y轴=幅度,X轴=深度类别)。

在这个数据集中,地震深度变量范围从40到680.我想将1000个地震深度观测值变成8个类别,例如: 40 - 120,121 - 200,... 600 - 680.然后,我想根据深度类别取平均震级,并将其绘制在折线图上。

我感谢任何帮助。 谢谢!

4 个答案:

答案 0 :(得分:9)

首先使用cut进行深度分类:

depth.class <- cut(quakes$depth, c(40, 120, 200, 300, 400, 500, 600, 680), include.lowest = TRUE)

(请注意,您的类定义可能需要根据您的具体情况而变化,并给出cut()行为的详细信息)。

找出每个depth.class中的平均幅度(假设没有NA):

mean.mag <- tapply(quake$mag, depth.class, mean)

(为适当的缺失值的数据集添加na.rm,例如mean.mag <- tapply(quake$mag, depth.class, mean, na.rm = TRUE))。

绘制成一条线:

plot(mean.mag, type = "l", xlab = "magnitude class")

将类标签放在X轴上是一项额外的工作,但此时你可能会质疑线图是否真的适合这里。

快速刺伤,关闭轴,然后直接从切割因子中提出类:

plot(mean.mag, type = "l", xlab = "magnitude class", axes = FALSE)
axis(1, 1:nlevels(depth.class), levels(depth.class))
axis(2)
box()

答案 1 :(得分:4)

线图在这里没用;点之间的线条在数据中表示什么关系?也许点图可能有用吗?

cats <- with(quakes, cut(depth, breaks = seq(40L, max(depth), by = 80), 
                         include.lowest = TRUE))
dat <- aggregate(mag ~ cats, data = quakes, FUN = mean)
with(dat, dotchart(mag, group = cats, xlab = "Mean Magnitude"))

产生:

enter image description here

答案 2 :(得分:2)

你确定你想要一个线图吗?我不确定这是最合适的情节。无论如何,这里的技巧是使用cut来适当地对数据进行分区,然后使用众多聚合工具之一来查找这些组的平均大小。最后,我们将绘制这些聚合值。我喜欢ggplot2plyr中的工具来执行以下任务:

library(ggplot2)
df <- quakes
df$bins <- with(df, cut(depth, breaks = c(0,40, 120, 200, 280, 360, 440, 520, 600, 680)))
df.plot <- ddply(df, .(bins), summarise, avg.mag = mean(mag))
qplot(bins, avg.mag, data = df.plot)

#If you want a line plot, here's one approach:
qplot(as.numeric(bins), avg.mag, data = df.plot, geom = "line") + 
xlim(levels(df.plot$bins))

答案 3 :(得分:2)

我同意你可能不想要一个直线图,而是一个dotplot()或某种箱形图。

您可以使用格子包中的带状疱疹轻松完成此操作:

library(lattice)
x <- runif(100)
y <- runif(100)
bwplot(~x|equal.count(y))

shingle()替换为equal.count()将允许您指定间隔,而不是允许R为您选择它们​​。

box plots with shingles