在R中用箱线图重叠
我试图使用在R中用箱线图重叠,r,ggplot2,lapply,R,Ggplot2,Lapply,我试图使用lappy在R中创建许多方框图。当我使用ggplot函数创建方框图时,我得到了正确的输出。当我尝试使用colnames通过lappy传递box plot函数时,函数无法按预期工作。随附正确的绘图和错误的绘图示例 doPlot = function(var1) { # Create the plot object ggobj = ggplot(wdbc_train, aes(x = diagnosis,y=var1)) + geom_boxplot() # Add som
lappy
在R中创建许多方框图。当我使用ggplot
函数创建方框图时,我得到了正确的输出。当我尝试使用colnames
通过lappy
传递box plot函数时,函数无法按预期工作。随附正确的绘图和错误的绘图示例
doPlot = function(var1) {
# Create the plot object
ggobj = ggplot(wdbc_train, aes(x = diagnosis,y=var1)) + geom_boxplot()
# Add some titles and axis labels
ggobj = ggobj + ggtitle(var1) + xlab("diagnosis") +
ylab(var1)
}
lapply(colnames(wdbc_train),doPlot)
正确的
不正确
您需要
从命名变量中获取数据
doPlot = function(var1) {
# Create the plot object
ggobj = ggplot(wdbc_train, aes(x = diagnosis, y=get(var1))) +
geom_boxplot()
# Add some titles and axis labels
ggobj = ggobj + ggtitle(var1) + xlab("diagnosis") + ylab(var1)
}
doPlot=函数(var1){
#创建打印对象
ggobj=ggplot(iris,aes(x=Species,y=get(var1)))+geom_箱线图()
#添加一些标题和轴标签
ggobj=ggobj+ggtitle(var1)+xlab(“物种”)+ylab(var1)
}
p当您将var1
传递给函数doPlot
时,它只是一个字符串。它需要被解释为dataframe的一列
我们可以将非标准评估(NSE)与sym
和一起使用代码>这里
library(ggplot2)
library(rlang)
doPlot = function(df, var1) {
# Create the plot object
ggobj = ggplot(df, aes(diagnosis,y = !!sym(var1))) + geom_boxplot()
# Add some titles and axis labels
ggobj + ggtitle(var1) + xlab("diagnosis") + ylab(var1)
}
然后将其应用于在list\u plot
中提供绘图列表的每一列
list_plot <- lapply(colnames(wdbc_train), doPlot, df = wdbc_train)
list\u绘图谢谢Ronak!非常感谢。
list_plot <- lapply(colnames(wdbc_train), doPlot, df = wdbc_train)