R 将名称应用于图形 x 轴

R sapply name to graph x axis

我正在使用此函数在 r

中进行一些探索性分析
nums <- sapply(db, is.numeric)
sapply(db[,nums], function(x) {
  nome <- as.character(names(x))
  hist(x)
  lines(density(x, na.rm = T))

  })

如何将图中列的名称打印为 x 轴? 我试过 apply over matrix by column - any way to get column name? 但我无法弄清楚函数的第二部分以使其在这种情况下工作

一种方法是遍历列名:

nums <- sapply(db, is.numeric)
numsNames <- names(db)[nums]

sapply(numsNames, function(x) {
  hist(db[,x], xlab=x)
  lines(density(db[,x], na.rm = T))
})

您可以使用 mapply 将数据和其他参数带到 hist

num <- sapply(iris, is.numeric)
opar <- par(mfrow = c(2,2))
histDensity <- function(x, ...){
  hist(x = x, freq = FALSE, ...)
  lines(density(x, na.rm = TRUE))
}
mapply(histDensity, x = iris[, num], main = names(iris[, num]))
par(opar)

或者,您可以使用 ggplot

library(reshape2)
library(ggplot2)
iris2 <- melt(iris)
ggplot(iris2, aes(x = value, y = ..density..)) + 
  geom_histogram() +
  geom_density() +
  facet_wrap(~variable)