【问题标题】:Iterating over a excel file and ploting a 2 columns comparison遍历 excel 文件并绘制 2 列比较
【发布时间】:2018-01-24 12:43:34
【问题描述】:

首先,我是一个初学者,所以我感谢您的耐心和时间来帮助我。我有一个包含 3 列的 excel 文件:Shopname、2016 和 2017,它们是用于比较的特定值。

我想遍历 excel 文件并绘制两个条形图,一个是 2016 年商店 X 的值,另一个是 2017 年的值。

我把我写到现在为止的东西贴在这里,我可以看到印刷品,但看不到情节......我能做得更好吗?

> #importing excel file
> #and ploting each line comparison between 2 columns
> library(xlsx)
> xl_data <- read.xlsx("File.xlsx", "Plan1")
> df<- data.frame(xl_data)
> # plot using facets
>   ggplot(aes(x=time, y=sold, group=shop)) +geom_bar(stat="identity")+ 
facet_grid(.~xl_data)

【问题讨论】:

  • 你没有在你的循环中使用你的循环变量i
  • @LAP 感谢您的回答。我真的忘记了 i 变量。我试图修复它,但在迭代时仍然没有绘图。你还有别的想法吗?我要更新我的问题中的代码
  • 您的数据是什么样的?你能给我们举个例子吗?您可以使用dput(head(df)) 为第一行生成代码。
  • structure(list(LOJAS = structure(1:4, .Label = c("CD NEREU", "LJ CANOINH", "LJ MAL338", "LJ SBENTO"), class= "factor "), X2016 = c(168459.86, 14480.03, 21095.07, 43290.47), X2017. = c(223637.46, 80006.86, 62768.54, 43168.34)), .Names = c("LOJAS", "X2016", "X2") row.names = c(NA, 4L), class= "data.frame")

标签: r excel plot


【解决方案1】:

阿方索, 你不需要一个循环。实现它的一种方法是使用 ggplot 的刻面功能:

#### load needed libraries
library(tidyr)
library(ggplot2)

### load  data -- this is coming from Excel
dt <- tribble(
  ~LOJAS,     ~y2016,    ~y2017,
  "CD NEREU"  , 168459.86, 223637.46,
  "LJ CANOINH",  14480.03,  80006.86,
  "LJ MAL338" ,  21095.07,  62768.54,
  "LJ SBENTO" ,  43290.47,  43168.34)

### arrange data for plotting
dt %>% 
  gather(time, sold, y2016, y2017)  %>% 

  # plot using facets
  ggplot(aes(x=time, y=sold, group=LOJAS)) +
    geom_bar(stat="identity") +
    facet_grid(.~LOJAS)

【讨论】:

  • 我将 group= 留在那里,因为我真的认为在这种情况下按商店分组的线图比按商店条形图分面的图更好
  • 这里 ts 是我的数据结构: structure(list(LOJAS = structure(1:4, .Label = c("CD NEREU", "LJ CANOINH", "LJ MAL338", "LJ SBENTO "), class= "因子"), X2016 = c(168459.86, 14480.03, 21095.07, 43290.47), X2017. = c(223637.46, 80006.86, 62768.54, 43168.34)", ".Names = c("2LOJAS" , "X2017."), row.names = c(NA, 4L), class= "data.frame")
  • 我没有成功复制你的例子,我是一个非常初学者哈哈哈,谢谢你帮助我
  • @AfonsoO.Lenzi,我已经用你的数据和适当的情节更新了答案。那是你要找的吗?谢谢!
  • 是的!就是这样,我只是不知道如何阅读 excel 并将其转换为 tribble 部分,非常感谢 Dan!
猜你喜欢
  • 2017-10-02
  • 2016-08-29
  • 2017-08-06
  • 2020-12-28
  • 1970-01-01
  • 2013-08-28
  • 2017-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多