[英]How can I make this plot for each column in my data frame using sapply and ggplot2?
我想為下面名為df的數據框中的每列數據制作相同的圖。
編輯: 為了澄清,我想為每一列(警察,警察,豎琴)等制作一個新的情節,因為在我的實際數據中我有很多(即在很多地方嘗試和網格在一個圖上)我希望能夠為每列創建下面的圖表。
樣本數據:
day <- c('5-Aug', '5-Aug','5-Aug','10-Aug','10-Aug','10-Aug','17-Aug','17-Aug','17-Aug')
station <- c(1:3,1:3,1:3)
Cop.Mean <- c(382, 1017, 1519, 698, 5398, 2458, 346, 5722, 6253)
CopN.Mean <- c(233, 167, 530, 36, 124, 20, 427, 1768, 1486)
Harp.Mean <- c(20, 482, 10, 8, 4014, 7, 4, 46, 1)
df <- data.frame(day,station,Cop.Mean, CopN.Mean, Harp.Mean)
我的情節:
library(ggplot2)
library(scales)
Cop.Plot <- ggplot(data=df, aes(x=station, y=Cop.Mean)) +
geom_point() + facet_grid(.~day)
print(Cop.Plot)
我想為這個例子中的三列數據(即df [3:5])中的每一列創建這個圖,但是無法弄清楚如何引用aes()中的多個列。 (即
aes(x=station, y=df[3:5])
不起作用。 我也試過了
i=df[3:5]
aes(x=station, y=i)
但我想我可能沒有使用正確的方法。 有人會非常友好地指出我正確的方向嗎? 這似乎是學習如何做的非常有用的工具,我非常渴望這樣做!
library(ggplot2)
library(reshape2)
moltendf <- melt(df, id.vars=c("day","station"))
allplots <- ggplot(data=moltendf, aes(x=station, y=value)) +
geom_point() + facet_grid(variable ~ day)
但我不清楚你是否想要它們所有的一個大的情節或你想*apply
每個cop.type *apply
和創建/保存許多不同的情節。 如果是后者,則可以使用熔融數據:
plotfun <- function(x,y) {
a <- ggplot(data=x, aes(x=station, y=value)) +
geom_point() + facet_grid(.~ day)
pdf(paste0(y,".pdf"))
print(a)
dev.off()
}
mapply(plotfun, split(moltendf, moltendf$variable), as.list(1:3))
正如baptiste所提到的, reshape2
包將幫助你。 這是完整的代碼:
library(reshape2)
df <- melt(df, id = c("day", "station"))
Cop.Plot <- ggplot(data = df, aes(x = station, y = value)) + geom_point()
Cop.Plot + facet_grid(variable ~ day)
我建議將day
作為一個因素並按時間順序排序水平:
day <- factor(day, levels = c('5-Aug', '10-Aug', '17-Aug'))
否則,它們按字母順序排序。
這是你的想法嗎?
library(reshape2)
ggdata <- melt(df,id=1:2,variable.name="Measure",value.name="Mean")
ggplot(ggdata,aes(x=station, y=Mean)) +
geom_point() +
facet_grid(Measure~day)
產生這個:
請注意,日期順序錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.