简体   繁体   中英

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)

will yield在此处输入图片说明

for loops are discouraged as they are slow. 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.

If you really need an apply-family function of plotters to have only one argument, the following will do:

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. You can format your data to longer and then filter the desired variables. Using facets and geom_density() you can avoid issues with titles. 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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM