如何从同一绘图上的单个文件获取多年 Y 轴数据?

发布于 2024-10-11 01:05:19 字数 729 浏览 6 评论 0原文

我有三年来的燃气表读数,我试图用 R 绘制图表,以突出显示一年中几个月的每日使用情况变化,并比较不同年份的使用情况。

数据示例:

Date,Gas  
02/01/2010,4460.9  
13/01/2010,4543  
04/02/2010,4656  
16/02/2010,4733  
07/03/2010,4842  
26/03/2010,4933.8  

我可以根据定期读数计算平均每日使用情况,并将几年内的整个数据绘制为单个数据系列:

A <- read.table("energy.csv", header=TRUE, fill=TRUE, sep=',')
A$Dates <- as.Date(A$Date, format="%d/%m/%Y")
for (j in 2:length(A$Gas)) {
  A$GasDiff[j-1] = A$Gas[j] - A$Gas[j-1]
}
plot(A$Dates, A$GasDiff, type="o", lty=1, pch=20, ylab="Daily Consumption",
     main="Gas Consumption")

但我不知道如何让 R 自动将数据拆分为不同的数据?框架?每年,这样我就可以为每年绘制单独的线。我可以仅使用每年的数据手动创建不同的输入文件,但它不优雅,并且每年都需要更改代码。

我确信这是一个简单的问题,但我盯着手册看,但无法弄清楚。

I have gas meter readings over three years which I'm trying to graph in R, to highlight the changing daily usage over the months in a year, and to compare different years' usage.

Data sample:

Date,Gas  
02/01/2010,4460.9  
13/01/2010,4543  
04/02/2010,4656  
16/02/2010,4733  
07/03/2010,4842  
26/03/2010,4933.8  

I can calculate the average daily usage from the periodic readings, and plot the whole of the data across several years as a single data series:

A <- read.table("energy.csv", header=TRUE, fill=TRUE, sep=',')
A$Dates <- as.Date(A$Date, format="%d/%m/%Y")
for (j in 2:length(A$Gas)) {
  A$GasDiff[j-1] = A$Gas[j] - A$Gas[j-1]
}
plot(A$Dates, A$GasDiff, type="o", lty=1, pch=20, ylab="Daily Consumption",
     main="Gas Consumption")

But I can't figure out how to get R to automatically split the data into different ?frames? for each year, so that I can plot separate lines for each year. I can manually create different input files with just the data for each year, but it's inelegant, and will need the code changed every year.

I'm sure it's a simple question, but I've stared at manuals, and can't figure it out.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

灯下孤影 2024-10-18 01:05:19

无需按年份将数据拆分为数据框;您可以很容易地使用 ggplot2 包来按年份区分绘图。首先,我将组成一些数据:

dts <- as.Date("20050101", '%Y%m%d') + seq(0,1000,15)
A <- data.frame( Dates = dts, Gas = 4000 + cumsum(abs( rnorm(length(dts), 100, 30))))

接下来,我将向 A 添加两列:DayOfYear,它是一年中的“日数”,以及 >GasDiff 列(与您的相同,但生成更容易,没有循环!):

A <- transform( A,               
               Year = format(Dates, '%Y'),
               DayOfYear = as.numeric( format(Dates, '%j')),
               GasDiff = c(diff( Gas ),NA))

接下来,我们使用 ggplot2 首先依次绘制所有年份,但具有不同的颜色:

require(ggplot2)
ggplot(A, aes(Dates, GasDiff)) + geom_line( aes(colour = Year))

这给你这个:
alt text

或者,您可以在垂直网格中绘制不同的年份:

ggplot(A, aes(DayOfYear, GasDiff)) + geom_line( )  + facet_grid(Year ~ .)

您会得到以下结果:
alt text

更新: 第三种方法是绘制所有在具有不同颜色/点的同一个地块上的年份,如果您正在寻找季节性模式,这可能很有用(但在我的情况下看起来很糟糕,因为我编写了随机数据)。

ggplot(A, aes(DayOfYear, GasDiff)) + 
  geom_line( aes(colour = Year) )  + 
  geom_point( aes(shape = Year))

替代文字

There's no need to split the data into data-frames by year; you can use the ggplot2 package quite easily to differentiate the plots by year. First I'll make up some data:

dts <- as.Date("20050101", '%Y%m%d') + seq(0,1000,15)
A <- data.frame( Dates = dts, Gas = 4000 + cumsum(abs( rnorm(length(dts), 100, 30))))

Next I'll add two columns to A: DayOfYear which is the "day-number" within the year, and the GasDiff column (same as yours but generated more easily, with no loops!):

A <- transform( A,               
               Year = format(Dates, '%Y'),
               DayOfYear = as.numeric( format(Dates, '%j')),
               GasDiff = c(diff( Gas ),NA))

Next we use ggplot2 to first plot all the years one after the other, but with different colors:

require(ggplot2)
ggplot(A, aes(Dates, GasDiff)) + geom_line( aes(colour = Year))

which gives you this:
alt text

Alternatively you can plot the different years in a vertical grid:

ggplot(A, aes(DayOfYear, GasDiff)) + geom_line( )  + facet_grid(Year ~ .)

and you get this:
alt text

UPDATE: A third way is to plot all the years on the same plot with different colors/points, which may be useful if you are looking for seasonal patterns (but looks bad in my case because I made up random data).

ggplot(A, aes(DayOfYear, GasDiff)) + 
  geom_line( aes(colour = Year) )  + 
  geom_point( aes(shape = Year))

alt text

被你宠の有点坏 2024-10-18 01:05:19

以下是与 Prasad 的 ggplot 示例 (1) 相对应的图,该示例使用lattice中的xyplot完成。 (2) 之后,我们展示如何使用 Zoo 包中的 xyplot.zoo 来完成此操作,然后 (3) 我们展示如何使用 plot.zoo 再次完成每个操作> 它使用了 Zoo 包的经典图形工具。

在每种情况下,我们还展示了基于 xblocks 的第四种样式。

首先让我们重复 Prasad 的设置:

dts <- as.Date("20050101", '%Y%m%d') + seq(0,1000,15)
A <- data.frame( Dates = dts, Gas = 4000 + cumsum(abs( rnorm(length(dts), 100, 30))))

A <- transform( A,               
               Year = format(Dates, '%Y'),
               DayOfYear = as.numeric( format(Dates, '%j')),
               GasDiff = c(diff( Gas ),NA))

现在让我们尝试使用lattice

library(lattice) # xyplot
library(latticeExtra) # layer_, panel.xblocks
library(gridExtra) # grid.arrange
library(RColorBrewer) # brewer.pal

png("png1.png")
p1 <- xyplot(GasDiff ~ Dates, group = Year, A, type = "l",
    par.settings = list(superpose.line = list(col = 1:nlevels(A$Year))),
    auto.key = list(lines = TRUE, points = FALSE))

p2 <- xyplot(GasDiff ~ DayOfYear | Year, A, type = "l", layout = c(1, 3))

p3 <- xyplot(GasDiff ~ DayOfYear, A, group = Year, type = "l",
    auto.key = list(lines = TRUE, points = FALSE))

# and here is another style:

myPalette <- brewer.pal(nlevels(A$Year), "Set3")
p4 <- xyplot(GasDiff ~ Dates, A, type = "l", col = 1) + 
    layer_(panel.xblocks(A$Dates, myPalette[A$Year]))

grid.arrange(nrow = 2, p1, p2, p3, p4)
dev.off()

这给出了这 4 个图:

alt text

现在让我们使用 using 重复这个Zoo 与lattice和其他包结合使用:

png("png2.png")
library(zoo)
library(lattice)
library(latticeExtra) # layer_, panel.xblocks
library(gridExtra) # grid.arrange
library(RColorBrewer) # brewer.pal

z <- with(A, zoo(GasDiff, Dates))
year <- format(time(z), "%Y")

# split years into separate columns and plot
P1 <- xyplot(do.call("merge", split(z, year)), screen = 1, col = 1:3)

# split years into separate columns and use day.of.year as time
day.of.year <- function(x) as.numeric(format(x, "%j"))
zz <- read.zoo(A[c(1, 5, 3)], FUN = day.of.year, split = 3)
colnames(zz) <- unique(year)
P2 <- xyplot(na.approx(zz, na.rm = FALSE))

P3 <- xyplot(na.approx(zz, na.rm = FALSE), screen = 1, col = 1:3, auto.key = TRUE)

pal <- brewer.pal(nlevels(factor(year)), "Set3")
P4 <- xyplot(z, screen = 1) + layer_(panel.xblocks(time(z), pal[factor(year)]))

grid.arrange(nrow = 2, P1, P2, P3, P4)
dev.off()

这是输出:

alt text

第三组方法是使用动物园的经典图形,我们使用上面计算的相同的 zzzpal

library(zoo)
library(RColorBrewer) # brewer.pal

png("png3a.png")
plot(do.call("merge", split(z, year)), screen = 1, col = 1:3)
dev.off()
png("png3b.png")
plot(na.approx(zz, na.rm = FALSE))
dev.off()
png("png3c.png")
plot(na.approx(zz, na.rm = FALSE), screen = 1, col = 1:3)
legend("topleft", colnames(zz), lty = 1, col = 1:3, bty = "n")
dev.off()
png("png3d.png")
plot(z, type = "n")
xblocks(time(z), pal[factor(year)])
lines(z)
dev.off()

这是输出

替代文字

替代文字

替代文字

替代文字

Here are the plots corresponding to Prasad's ggplot examples (1) done using xyplot in lattice. (2) After that we show how to do it using xyplot.zoo from the zoo package and then (3) we show how to do each yet again using the plot.zoo which uses the zoo package's classic graphics facilities.

In each of these cases we also show a 4th style which is based on xblocks.

First lets repeat Prasad's setup:

dts <- as.Date("20050101", '%Y%m%d') + seq(0,1000,15)
A <- data.frame( Dates = dts, Gas = 4000 + cumsum(abs( rnorm(length(dts), 100, 30))))

A <- transform( A,               
               Year = format(Dates, '%Y'),
               DayOfYear = as.numeric( format(Dates, '%j')),
               GasDiff = c(diff( Gas ),NA))

Now lets try using lattice

library(lattice) # xyplot
library(latticeExtra) # layer_, panel.xblocks
library(gridExtra) # grid.arrange
library(RColorBrewer) # brewer.pal

png("png1.png")
p1 <- xyplot(GasDiff ~ Dates, group = Year, A, type = "l",
    par.settings = list(superpose.line = list(col = 1:nlevels(A$Year))),
    auto.key = list(lines = TRUE, points = FALSE))

p2 <- xyplot(GasDiff ~ DayOfYear | Year, A, type = "l", layout = c(1, 3))

p3 <- xyplot(GasDiff ~ DayOfYear, A, group = Year, type = "l",
    auto.key = list(lines = TRUE, points = FALSE))

# and here is another style:

myPalette <- brewer.pal(nlevels(A$Year), "Set3")
p4 <- xyplot(GasDiff ~ Dates, A, type = "l", col = 1) + 
    layer_(panel.xblocks(A$Dates, myPalette[A$Year]))

grid.arrange(nrow = 2, p1, p2, p3, p4)
dev.off()

This gives these 4 plots:

alt text

and now lets repeat this using using zoo in conjunction with the lattice and the other packages:

png("png2.png")
library(zoo)
library(lattice)
library(latticeExtra) # layer_, panel.xblocks
library(gridExtra) # grid.arrange
library(RColorBrewer) # brewer.pal

z <- with(A, zoo(GasDiff, Dates))
year <- format(time(z), "%Y")

# split years into separate columns and plot
P1 <- xyplot(do.call("merge", split(z, year)), screen = 1, col = 1:3)

# split years into separate columns and use day.of.year as time
day.of.year <- function(x) as.numeric(format(x, "%j"))
zz <- read.zoo(A[c(1, 5, 3)], FUN = day.of.year, split = 3)
colnames(zz) <- unique(year)
P2 <- xyplot(na.approx(zz, na.rm = FALSE))

P3 <- xyplot(na.approx(zz, na.rm = FALSE), screen = 1, col = 1:3, auto.key = TRUE)

pal <- brewer.pal(nlevels(factor(year)), "Set3")
P4 <- xyplot(z, screen = 1) + layer_(panel.xblocks(time(z), pal[factor(year)]))

grid.arrange(nrow = 2, P1, P2, P3, P4)
dev.off()

Here is the output:

alt text

A third set of ways is to use classic graphics with zoo where we use the same z, zz and pal calculated above:

library(zoo)
library(RColorBrewer) # brewer.pal

png("png3a.png")
plot(do.call("merge", split(z, year)), screen = 1, col = 1:3)
dev.off()
png("png3b.png")
plot(na.approx(zz, na.rm = FALSE))
dev.off()
png("png3c.png")
plot(na.approx(zz, na.rm = FALSE), screen = 1, col = 1:3)
legend("topleft", colnames(zz), lty = 1, col = 1:3, bty = "n")
dev.off()
png("png3d.png")
plot(z, type = "n")
xblocks(time(z), pal[factor(year)])
lines(z)
dev.off()

and here is the output

alt text

alt text

alt text

alt text

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文