【发布时间】:2016-12-21 15:27:49
【问题描述】:
我已经查看了与我的 ggplot 问题相关的关于堆栈溢出的上一个问题,但我无法找到明显有帮助的内容。
问题:如何修改下面的代码以使用循环为数据框中的每一列(变量)生成单独的频率图(直方图)。即 ID x 每个变量?
数据:
example.xlsx
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 1
Kay Largo 4 10 5 13
代码:
#set work DIR
setwd("C:/A")
library(rJava)
options(java.parameters = "-Xmx2048m") ## memory set to 2 GB
library(xlsx)
#read in .xlsx file and apply encoding UTF-8 (French accents)
DAT <- read.xlsx("example.xlsx", 1, encoding="UTF-8")
#plot data
library(ggplot2)
p <- ggplot(subset(DAT, a1.sum>1), aes(ID, a1.sum, y=a1.sum))
p <- p + geom_bar(stat="identity", fill="blue", color="green")
p <- p + 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())
p <- p + theme(axis.text.x=element_text(size=10,angle=90, hjust=1, face="plain", family="serif"))
p <- p + theme(axis.text.y=element_text(size=10, hjust=1, face="plain", family="serif"))
p <- p + theme(axis.line.x = element_line(color="black", size = 0.50),
axis.line.y = element_line(color="black", size = 0.5))
p
ggsave(filename="a1.png", plot=p)
输出:
a1.sum 的图 Example of plot output
尝试创建一个循环来为变量 b3、c6 和 d9 生成相同的图。
我使用 aes_string 尝试了几种不同的方法。以下是我尝试设置循环的方式:
#get variable names that end in .sum
n <- names(DAT[grep("*.sum",names(DAT))])
#loop through variable names
for (i in 1:length(n)){
in_dat <- c(n[i])
...ggplot...
print(p[i]);
}
【问题讨论】: