【问题标题】:Python vs. R in org-mode babel output graphicsorg-mode babel 输出图形中的 Python vs. R
【发布时间】:2018-04-27 02:53:10
【问题描述】:

我正在尝试以 org 模式编写报告。 从 csv 文件中读取数据(单列三行,浮点数),在条形图中进行比较,将图表嵌入到报告中,以便将其导出为 Latex,然后导出为 pdf。

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

我在 python 代码中做错了什么?如果我在交互模式下运行 python 代码,它会毫无问题地生成图表,但由于某种原因,当我通过 cell-block 运行时,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 org-mode export-to-pdf org-babel


    【解决方案1】:

    我相信你的 python 代码块的标头值是错误的。 :results &lt;file name&gt; file:file &lt;file name&gt; 之间存在差异。根据文档(为清楚起见已编辑):

    :results file

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

    收藏 [...]

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

    类型 [...]

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

    :file &lt;file name&gt;

    保存代码执行结果的外部 :file 堵塞。 [...] 一些语言,例如“R”、“dot”、“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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多