R:如何在一张图表上绘制多个密度图,其中的列来自 excel

R: How do I plot multiple density plots on one chart, with columns pulled from excel

共有 R/programming 位新手。我正在尝试从 excel sheet 中获取列数据(多列),为每一列创建一个密度图,然后将它们绘制到一个图表上并使其看起来不错。

excel 数据只是包含数值的列(colA、colB、colC 等)(每列数据大约有 2000 个数据点)。我已经设法弄清楚如何绘制一列:

library(readxl)
setwd("directoryLocation")
dft <- read_excel("sample.xlsx", sheet="columns")
d <- density(dft$`colA`)
plot(d)

但我无法合并所有列。 任何关于如何进行(或更好的方法)的想法将不胜感激。 干杯!

你以后一定要包括一个可重现的例子,这样我就可以确定我回答的是正确的问题,但是 lattice 库应该让你接近:

library(stats)
library(lattice)
densityplot( ~ height | voice.part, data = singer, layout = c(2, 4),  
             xlab = "Height (inches)", bw = 5)

感谢您的建议; lattice 看起来像是另一种很棒的方法!很抱歉不清楚,这是我试图做的以及我是如何解决它的:

  1. 数据(excel 电子表格中的列...每列大约 2000 行):
  • colA colB colC ...
  • 34.4 65.5 55.1 ...
  • 34.6 64.5 54.6 ...
  1. 我想做的是提取这些 excel 电子表格列中的数据并为每一列绘制密度图,但使用相同的轴(所以一个图表,多个图)

  2. 我是这样实现的:

注意:我意识到每列中的第一个单元格是“header”,我可以使用 [=15= 将数据框中的那些 header 名称调用到每个新情节中]

plot(density(dataFrameName$headerName)) for the first one, and then lines(density(dataFrameName$headerName)) for each additional data column.

library(readxl)
setwd("pathToWorkingDir")

dft <- read_excel("excelSpreadsheet.xlsx", sheet="sheetName")

tiff("createPlotImage.tiff", height = 8, width = 8, units = 'in', res=300)
plot(density(dft$`colA`), panel.first = abline(h=0,col="black"), xlim = c(-60,-45), ylim =c(0,1.5), lwd=3, col='#FF0000', main = "", cex.axis = 1.4, ann=FALSE)
lines(density(dft$`colB`), lwd=3,col='#FF9900')
lines(density(dft$`colC`), lwd=3,col='#FFFF00')
legend('topleft',bty="n",c('colA','colB','colC'), ncol=1, col=c('#FF0000','#FF9900','#FFFF00','#66FF66'),text.width = 6, lwd = 3,cex = 1)

dev.off()

结果: plot of the code