在@Nick Criswell的帮助下,我学会了如何使用 ggplot2 和 aes_string 创建make plot函数和 lapply 。 loop Freq plot with GGPLOT aes_string
我无法修改代码以仅绘制大于给定阈值的值。在使用函数方法之前,我编写了以下有效的代码:
p <- ggplot(subset(DAT, al.sum>10), aes(word, al.sum, y=freq))
问题:如何修改以下代码以仅绘制超过给定阈值的值?即如果计数大于10,我只希望每条记录都包含在频率图中。从下面的代码中只有这个条件的al.sum只有Dot_Matricks会包含在图中。
#set work DIR
setwd("C:/A")
#Data create
DAT <- read.table(text = "ID a1.sum b3.sum c6.sum d9.sum
April_Showers 10 5 15 0
Anita_Job 2 3 1 14
Candy_Cain 4 7 14 17
Crystal_Ball 6 8 16 12
Dot_Matricks 15 9 0 1
Kay_Largo 4 10 5 13",
header = TRUE, stringsAsFactors = FALSE)
#Plot Data function
library(ggplot2)
make_plots = function(data, column){
ggplot(data, aes_string(x = "ID", y=column)) +
geom_bar(stat="identity", fill="blue", color="green") +
theme(plot.background = element_rect(fill = "white"),
panel.background = element_rect(fill = "white"),
panel.grid.major = element_line(colour = "white",size=0.25),
panel.grid.minor = element_blank(),
axis.text.x=element_text(size=10,angle=90, hjust=1,
face="plain", family="serif"),
axis.text.y=element_text(size=10, hjust=1, face="plain", family="serif"),
axis.line.x = element_line(color="black", size = 0.50),
axis.line.y = element_line(color="black", size = 0.5))
}
#lapply function
myplots <- lapply(colnames(DAT[2:ncol(DAT)]), make_plots, data = DAT)
#collect names of each col that end with .sum
n <- names(DAT[grep("*.sum",names(DAT))])
#save each plot as .png
for (i in 1:length(n)){
print(myplots[i])
ggsave(filename=paste0(i,".png"))
}
答案 0 :(得分:2)
这应该可以解决问题:
GraphSearch
您也可以使用子集功能执行此操作。如果您想将图表返回到R会话,请注释ggsave行并取消注释make_plots = function(data, column,Threshold){
PltData <- data[data[,column] >Threshold,]
Plt <- ggplot(PltData, aes_string(x = "ID", y=column)) +
geom_bar(stat="identity", fill="blue", color="green") +
theme_bw()+
theme(
panel.grid.major = element_line(colour = "white",size=0.25),
panel.grid.minor = element_blank(),
axis.text.x=element_text(size=10,angle=-30, hjust=0)
)
# Plt
ggsave(Plt,filename=paste0(column,".png"))
}
lapply(colnames(DAT[2:ncol(DAT)]), make_plots, data = DAT,Threshold=10)
。