我正在尝试以组织模式撰写报告。 从csv文件中读取数据(单列三行,浮动数字),在条形图中进行比较,将图表嵌入到报告中,以便可以将其导出到乳胶,然后导出到pdf。
我很难理解我在Python代码的条形创建部分中所做的事情,因为R_plot工作正常,这意味着图表在相同的组织模式
: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
我相信你的 python 代码块的标头值是错误的。
:results <file name> file
和 :file <file name>
之间有区别。根据文档(为了清晰起见进行了编辑):
:results file
有四类 :results 标头参数。每个“src”代码 块每类只能有一个选项。 [...]
收藏[...]
- 值默认。功能模式。结果是“src”代码块中最后一条语句返回的值。像Python这样的语言可能 需要在“src”代码块中显式返回语句。用法 示例: :结果值。
类型 [...]
- file 解释为文件的路径。插入文件的链接。使用示例::结果值文件。
:file <file name>
保存代码执行结果的外部:文件 堵塞。 [...]某些语言,例如‘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