[英]How to label axes on a plot when making a custom function?
I need to make a custom function that would be draw several separate boxplot graphs.我需要制作一个自定义函数来绘制几个单独的箱线图。 My function has two arguments: one for the x-axis, another for the y-axis.我的函数有两个参数:一个用于 x 轴,另一个用于 y 轴。 I want to label them with the names of the columns from my data frame that I'm using as arguments.我想用我用作参数的数据框中的列的名称来标记它们。 The problem is when I use colnames()
to extract column names it doesn't show anything on the graph, not even the letters a
and b
that are used as arguments (it used to show them when I didn't have the labs()
layer).问题是当我使用colnames()
提取列名时,它不会在图表上显示任何内容,甚至不显示用作参数的字母a
和b
(它曾经在我没有labs()
时显示它们labs()
层)。 Can you help me fix this?你能帮我解决这个问题吗? My code is below.我的代码如下。
forestfires <-
read.csv(url(
"https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv"))
require(ggplot2)
boxplot_months <- function(a,b) {
ggplot(data = forestfires) +
aes_string(x=a, y=b) +
geom_boxplot() +
theme(panel.background = element_rect(fill="white")) +
labs(x=colnames(a), y=colnames(b))
}
boxplot_months(forestfires$month, forestfires$FFMC)
aes_string
takes characters as input. aes_string
将字符作为输入。
That being said, by passing the arguments as strings, you can use a
and b
in labs()
as well.话虽如此,通过将参数作为字符串传递,您也可以在labs()
使用a
和b
。 However, I should mention that colnames(forestfires$month)
is simply none since after extracting a column you simply have a vector not that column anymore.但是,我应该提到colnames(forestfires$month)
根本就没有,因为在提取一列之后,您只是拥有一个不再是该列的向量。
forestfires <-
read.csv(url(
"https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv"))
boxplot_months <- function(a,b, mydataset) {
require(ggplot2)
ggplot(mydataset) +
geom_boxplot(aes_string(a,b)) +
theme(panel.background = element_rect(fill="white"))+
labs(x=a, y=b)
}
boxplot_months("month", "FFMC", forestfires)
Created on 2019-06-26 by the reprex package (v0.3.0)由reprex 包(v0.3.0) 于 2019 年 6 月 26 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.