我有一个名为response的变量.这个变量将传递给ggplot包中的facet_wrap()
response<-"job"
Run Code Online (Sandbox Code Playgroud)
当我直接在facet_wrap()中指定变量时
例如
ggplot(data,aes(job,fill=class )) + geom_bar() +facet_wrap(~job)
Run Code Online (Sandbox Code Playgroud)
它给出了必要的情节
但是当我在facet_wrap()中指定响应变量时
ggplot(data,aes(job,fill=reponse))+ geom_bar() + facet_wrap(~get(paste(response)))
Run Code Online (Sandbox Code Playgroud)
我收到错误
At least one layer must contain all variables used for facetting
Run Code Online (Sandbox Code Playgroud)
是否有方法facet_wrap可以从响应变量接受变量名称,而不是直接在其中编写变量名称
我正在编写一个函数来生成股票价格的时间序列图.但是,我收到以下错误
eval中的错误(expr,envir,enclos):找不到对象'df1234'
这是函数的一个例子:
plot.prices <- function(df1234) {
require(ggplot2)
g <- ggplot(df1234, aes(x= as.Date(Date, format= "%Y-%m-%d"), y= df1234[, 3],
colour= brewer.pal(12,"Set3")[1])) + geom_point(size=1)
g + geom_point(aes(x= date, y = df1234[, 4],
colour= brewer.pal(12,"Set3")[2]), size=1)
# ... code not shown...
g
}
Run Code Online (Sandbox Code Playgroud)
示例数据:
spy <- read.csv(file= 'http://ichart.finance.yahoo.com/table.csv?s=SPY&d=11&e=1&f=2012&g=d&a=0&b=29&c=1993&ignore=.csv', header= T)
plot.prices(spy) # produces error
g <- ggplot(spy, aes(x= as.Date(Date, format= "%Y-%m-%d"), y= spy[, 3],
colour= brewer.pal(12,"Set3")[1])) + geom_point(size=1)
g + geom_point(aes(x= as.Date(Date), y = spy[, 4],
colour= brewer.pal(12,"Set3")[2]), size=1)
## does not …Run Code Online (Sandbox Code Playgroud) 我有一系列的ggplot图表,我正在重复一些小的变化.我想将这些qplots的选项包装成一个函数,以避免代码中的大量重复.
我的问题是,对于某些图表,我使用的是+ facet_wrap()选项,但对于其他图表,我不是.即我需要facet wrap作为可选参数.当包含它时,代码需要使用facets参数中提供的变量调用+ facet_wrap().
理想情况下,我的函数看起来像这样,facet是一个可选参数:
$ qhist(variable, df, heading, facets)
Run Code Online (Sandbox Code Playgroud)
我已经尝试使用谷歌搜索如何添加可选参数,他们建议传递一个默认值或使用带有missing()函数的if循环.我无法上班.
这是我编写的函数,包含了可选facet参数的所需功能.
$ qhist <- function(variable, df, heading, facets) {
qplot(variable, data = df, geom = "histogram", binwidth = 2000,
xlab = "Salary", ylab = "Noms") +
theme_bw() +
scale_x_continuous(limits=c(40000,250000),
breaks=c(50000,100000,150000,200000,250000),
labels=c("50k","100k","150k","200k","250k")) +
opts(title = heading, plot.title = theme_text(face = "bold",
size = 14), strip.text.x = theme_text(size = 10, face = 'bold'))
# If facets argument supplied add the following, else do not add this code
+ facet_wrap(~ facets)
Run Code Online (Sandbox Code Playgroud) 我需要依靠来在函数内部生成图aes_string(),并且需要标签作为行名。
下面的图表可以正常工作,但不能在函数内部使用。
library(ggplot2)
data(mtcars)
plotfun <- function(cars) {
g <- ggplot(data = cars, aes_string(x = "mpg", y = "disp", label = "rownames(cars)"))
g <- g + geom_point()
g <- g + geom_text()
g
}
plotfun(cars = mtcars)
Run Code Online (Sandbox Code Playgroud)
当作为函数运行时,这使我:
Error: Aesthetics must either be length one, or the same length as the dataProblems:mpg, disp
Run Code Online (Sandbox Code Playgroud)
我不能把头缠住它。我知道关于函数内部存在很多类似的问题aes_string() –我只是无法使其解决方案适应我的问题。
附言:显然,以上MWE很愚蠢;在我的实际用例中,我通过for循环运行该图,因此需要使用aes_string()。