r - 将多个 Excel 工作表绘制成一张图表,无需重复 read.xlsx

标签 r excel plot xlsx

我有一个包含三张表的 Excel 文件:表 1、表 2、表 3。 每张纸都有 x 列和 y 列。 我想将三个图 x-y 放入一个图中,如下所示

enter image description here

我所做的是分别阅读每张纸,以及“情节+线条”。

有没有循环方法可以做到这一点?因为我会有超过三张纸。

最佳答案

我认为这里的一个好方法是将每个工作表读入数据框列表中,将它们堆叠到一个包含源工作表标识符的数据框中,然后使用 ggplot2 进行绘图。

下面是我创建的一个名为 test.xlsx 的简单 Excel 文件的示例。它有三张纸,每张纸有四行数据,如下图所示。该代码假定 Excel 文件位于当前工作目录中。如果没有,请在读取数据时提供适当的文件路径。我使用了 readxl 包来读取数据。此方法可推广到具有任意数量具有相同列名称的工作表的 Excel 工作簿(尽管您可以进行额外的处理来处理不同工作表中的不同列名称)。

library(readxl)
library(dplyr)
library(ggplot2)

# Get sheet names
sht = excel_sheets("test.xlsx")

sht
[1] "Sheet 3" "Sheet 2" "Sheet1"
# Read each sheet into a list
df = lapply(setNames(sht, sht), function(s) read_excel("test.xlsx", sheet=s))

df 
$`Sheet 3`
      x     y
1     1    10
2     2    11
3     3    12
4     4    13

$`Sheet 2`
      x     y
1     1     5
2     2     6
3     3     7
4     4     8

$Sheet1
      x     y
1     1     1
2     2     2
3     3     3
4     4     4
# Convert to a single data frame with a column for the source sheet
df = bind_rows(df, .id="Sheet")

# Plot
ggplot(df, aes(x,y,colour=Sheet)) +
  geom_line() +
  scale_y_continuous(limits=c(0,max(df$y))) +
  theme_classic()

enter image description here

关于r - 将多个 Excel 工作表绘制成一张图表,无需重复 read.xlsx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43593792/

相关文章:

c# - Excel 工作表选择更改事件第一次不会被触发,但第二次会起作用

.net - 如何在 Excel 宏中使用 JavaScript?

r - 使用 R 绘制交互图

R Shiny ggplot 对 varSelectInput 有反应

r - 如何将轴刻度线的限制调整为与 ggplot 中的边框相同?

VBA 处理多种自定义数据类型的可能性

python - 绘图后更改轴

R - 如何根据一列中的值汇总其他列

r - 如何读取 "Debian control file"(DCF)格式的数据?

python - 如何自定义并向 Sympy 图中添加额外元素?