繁体   English   中英

Python 与 R 在 org-mode babel output 图形中

[英]Python vs. R in org-mode babel output graphics

我正在尝试以组织模式编写报告。 从csv文件中读取数据(单列三行,浮点数),在条形图中进行比较,将图表嵌入到报表中,这样就可以导出到latex,再导出到pdf。

我很难理解我在 python 代码的条形图创建部分所做的事情,因为 R_plot 工作正常,这意味着图表在相同的 org-mode:export:results:file 设置下嵌入到报告中。

python 代码我做错了什么? 如果我在交互模式下运行 python 代码,它会毫无问题地生成图表,但由于某种原因,当我按单元块运行时,py_comparison.png 没有保存。

#+NAME: R_plot
#+BEGIN_SRC R :exports both :results output graphics :file r_comparison.png
# graph in R
library("ggplot2")
performance <- read.csv("comparison.csv", header=FALSE)$V1
df <- data.frame(resource = c("1node1core", "1node8core", "2node8core"), performance = performance)
p <- ggplot(data = df, aes(x=resource, y=performance)) +
     geom_bar(stat="identity", fill="steelblue") + 
     theme_minimal() +
     ggtitle("Computation time (min) vs. Resource (type)")
p
#+END_SRC

#+NAME: python_plot
#+BEGIN_SRC python :exports both :results output graphics :file py_comparison.png
import matplotlib.pyplot as plt; plt.rcdefaults()
import matplotlib.pyplot as plt
import csv

objects = ['1node1core', '1node8core', '2node8core']
y_pos = list(range(0, len(objects)))

performance = []
with open('comparison.csv', newline='') as csvfile:
  reader = csv.reader(csvfile)
  for row in reader:
    f_row = float(row[0])
    performance.append(f_row)

plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Time')
plt.title('Resource vs. Time')

plt.show()
#+END_SRC

+END_SRC

我相信您的python代码块标头值是错误的。 :results <file name> file:file <file name>之间有区别。 根据文档(为清晰起见,已编辑):

:results file

:results标头参数有四类。 每个类的每个“ src”代码块只能采用一个选项。 [...]

收藏 [...]

  • 值默认。 功能模式。 结果是“ src”代码块中最后一条语句返回的值。 像Python这样的语言可能需要在“ src”代码块中使用显式的return语句。 用法示例::results值。

输入 [...]

  • file解释为文件路径。 插入文件链接。 用法示例::结果值文件。

:file <file name>

外部:file,用于保存代码块的执行结果。 [...]一些语言,例如“ R”,“点”,“ ditaa”和“ gnuplot”会自动将源代码包装在其他样板代码中。 通过仅执行:file内容,此类代码包装有助于重新创建输出,尤其是图形输出。

在python中, plt.show() (或savefig )的结果为None ,该图像只是一个副作用,因此不会插入任何内容。 在R中工作是因为上面提到的样板包装器

因此,在python中,您需要保存并返回图像,而不是显示它。 这样的事情应该起作用:

#+NAME: python_plot
#+BEGIN_SRC python :results img.png file

import matplotlib.pyplot as plt
plt.plot(range(5))
plt.savefig('img.png')
return 'img.png'

#+END_SRC

保存 plot(如果你想将它保存在其他目录中,你可以这样做)并在结果中显示它......

#+begin_src python :results output file :file img.png :output-dir img/ :exports both
import sys
import matplotlib.pyplot as plt
plt.plot(range(5))
plt.savefig(sys.stdout.buffer

#+end_src

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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