[英]Adding individual titles from a vector to each R plots
For a function, I need to keep variable names in a vector and I use a function to plot density graphs of my variables.对于函数,我需要将变量名称保留在向量中,并使用函数来绘制变量的密度图。
My problem is as follows in summary ;我的问题总结如下;
var_names <- c("mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb")
plotter <- function(x){
plot(density(x),
main = "",
xlab = "",
ylab = "")
title(var_names)
}
par(mfrow=c(4,3),mar=c(1,1,1,1))
apply(mtcars,2,plotter)
Couldn't imagine how I can match them.无法想象我怎么能匹配他们。
var_names <- c("mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb")
plotter <- function(x, var){
plot(density(x[[var]]),
main = var,
xlab = "",
ylab = "")
}
par(mfrow=c(4,3),mar=c(2.1,2.1,2.1,1))
for(vn in var_names) plotter(mtcars, vn)
for
loops are discouraged as they are slow.不鼓励for
循环,因为它们很慢。 However in conjunction with plotting, which is slow in its own way or if the loop is only run for 11 times as in this example, for
loops are perfectly fine and beginner friendly.然而,与绘图结合使用,这本身很慢,或者如果循环只运行了 11 次,就像在这个例子中一样, for
循环非常好并且适合初学者。
If you really need an apply-family function of plotters to have only one argument, the following will do:如果您真的需要绘图仪的 apply-family 函数只有一个参数,则可以执行以下操作:
var_names <- c("mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb")
plotter <- function(x){
plot(density(x[[1]]),
main = names(x),
xlab = "",
ylab = "")
}
par(mfrow=c(4,3),mar=c(2.1,2.1,2.1,1))
sapply(1:11,function(n) plotter(mtcars[n]))
I would suggest a tidyverse
approach with ggplot2
and the vector of names you have.我建议使用ggplot2
和您拥有的名称向量的tidyverse
方法。 You can format your data to longer and then filter the desired variables.您可以将数据格式化为更长的格式,然后过滤所需的变量。 Using facets and geom_density()
you can avoid issues with titles.使用 facets 和geom_density()
可以避免标题问题。 Here the code:这里的代码:
library(tidyverse)
#Vector
var_names <- c("mpg","cyl","disp","hp","drat","wt","qsec","vs","am","gear","carb")
#Data
mtcars %>% pivot_longer(cols = everything()) %>%
filter(name %in% var_names) %>%
ggplot(aes(x=value))+
geom_density()+
facet_wrap(.~name,scales = 'free')+
theme_bw()
Output:输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.