迭代地子集数据帧并使用 R 应用于绘图函数
Posted
技术标签:
【中文标题】迭代地子集数据帧并使用 R 应用于绘图函数【英文标题】:Iteratively subset dataframes and apply to plot function using R 【发布时间】:2022-01-17 11:56:33 【问题描述】:给定一个数据框df
和绘制其子集sub1 <- df[, c('date', 'price', 'type')]
的代码如下:
df <- structure(list(date = c("2021-10-1", "2021-10-2", "2021-10-3",
"2021-10-4", "2021-10-5", "2021-10-6", "2021-10-7", "2021-10-8",
"2021-10-9", "2021-10-10", "2021-10-11", "2021-10-12", "2021-10-13",
"2021-10-14"), value = c(190.3, 174.9, 163.2, 168.4, 168.6,
168.2, 163.5, 161.6, 172.9, 166.5, 175.2, 197.7, 212.1, 177.9
), price = c(191.3, 175.9, 164.2, 169.4, 169.6, 169.2, 164.5,
162.6, 173.9, 167.5, 176.2, 198.7, 213.1, 178.9), quantity = c(192.3,
176.9, 165.2, 170.4, 170.6, 170.2, 165.5, 163.6, 174.9, 168.5,
177.2, 199.7, 214.1, 179.9), type = c(1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L)), class = "data.frame", row.names = c(NA,
-14L))
要绘制的代码:
df$date <- as.Date(df$date)
df$type <- as.factor(df$type)
df %>%
select(date, price, type) %>%
mutate(date = as.Date(date)) %>%
rename(value = price) %>%
ggplot(aes(x=date, y=value, group=type, color = type, fill = type)) +
geom_area(alpha=0.4, position = "identity") +
theme(
text = element_text(size=20),
plot.margin=unit(c(1, 1, 1.5, 1.2), 'cm')
) +
scale_y_continuous(breaks = range(df$value),
expand = expansion(mult = c(0, 0.1), add = c(1, 0))) +
scale_x_date(breaks = range(df$date))
ggsave(filename = './value.png', device = 'png')
输出:
现在,我希望迭代生成多个子数据帧,比如(请注意date
和type
是两个常见的列):
sub1 <- df[, c('date', 'value', 'type')]
sub2 <- df[, c('date', 'price', 'type')]
sub3 <- df[, c('date', 'quantity', 'type')]
...
并将所有数据框循环到绘图代码,最后使用value.png
,price.png
,...的名称一一保存。
我怎么能在 R 中做到这一点?非常感谢。
EDIT1:
lapply(c("value", "price", "quantity"), function(variable)
png(paste0(variable, ".png"))
ggplot(aes(x=date, y=value, group=type, color = type, fill = type)) +
geom_area(alpha=0.4, position = "identity") +
theme(
text = element_text(size=20),
plot.margin=unit(c(1, 1, 1.5, 1.2), 'cm')
) +
scale_y_continuous(breaks = range(df$value),
expand = expansion(mult = c(0, 0.1), add = c(1, 0))) +
scale_x_date(breaks = range(df$date))
dev.off())
【问题讨论】:
类似lapply(c("value", "price", "quantity"), function(variable) png(paste0(variable, ".png")...); ggplot(... y=variable...); ... dev.off() )
我更新了我的试用码,还不行,请检查一下。
【参考方案1】:
我用for循环,可以,欢迎分享其他解决方案:
df$date <- as.Date(df$date)
df$type <- as.factor(df$type)
cols <- c('value', 'price', 'quantity')
for (col in cols)
p <- df %>%
select(date, col, type) %>%
mutate(date = as.Date(date)) %>%
rename(value = col) %>%
ggplot(aes(x=date, y=value, group=type, color = type, fill = type)) +
geom_area(alpha=0.4, position = "identity") +
theme(
text = element_text(size=20),
plot.margin=unit(c(1, 1, 1.5, 1.2), 'cm')
) +
scale_y_continuous(breaks = range(df$value),
expand = expansion(mult = c(0, 0.1), add = c(1, 0))) +
scale_x_date(breaks = range(df$date))
print(p)
输出:
【讨论】:
以上是关于迭代地子集数据帧并使用 R 应用于绘图函数的主要内容,如果未能解决你的问题,请参考以下文章