我想编写一个函数,它接受一个数据帧,并将该数据帧中的所有列绘制为直方图.
I want to write a function that takes a dataframe, and graphs all the columns in that dataframe as histograms.
对于我事先知道其列名的数据框,我可以写
For a dataframe whose column names I know beforehand, I can write
qplot(colname1, data=df, geom='histogram')
qplot(colname2, data=df, geom='histogram')
...
但我想一般地这样做,以便我可以将列的名称用作字符串 "colname1"
.
but I want to do this generically, so that I can use the name of the column as a string "colname1"
.
也就是说,怎么写
plot_histogram_of_column <- function(df, colname) {
# qplot(colname, data=df, geom='histogram') won't work
}
使用 ggplot
和 aes_string
.像这样的:
Use ggplot
and aes_string
. Something like this:
ggplot(data = df, aes_string(x = colname)) + geom_histogram()
aes_string
正是为此目的而编写的.
aes_string
was written precisely for this purpose.