python - org-mode babel 输出图形中的 Python vs. R
问题描述
我正在尝试以 org-mode 编写报告。从 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 头参数有四类。每个“src”代码块每个类只能采用一个选项。[...]
收藏[...]
- 值 默认值。功能模式。结果是“src”代码块中最后一条语句返回的值。像 Python 这样的语言可能需要在“src”代码块中显式地返回语句。使用示例::results 值。
类型[...]
- file 解释为文件的路径。插入文件的链接。用法示例: :results 值文件。
保存代码块执行结果的外部 :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
推荐阅读
- batch-file - Xcopy 随机选择
- swift - swift中的选择器问题
- laravel - 如何为 JSON laravel 编写验证规则?
- ios - LocationManager requestWhenInUseAuthorization 中的语法错误
- javascript - Expo OTA 更新:app.json 中的更新版本?
- python - Django中的酒店预订系统:如何使房间在一段时间内对其他用户不可用
- cupy - 将数组的列作为向量执行“for循环”时,Cupy 比 numpy 慢
- r - 估计较小样本量的功效 - simr 包
- android - 如何在 Fragment 中创建选项菜单?
- spring - 如何将用户重定向到登录页面(如果尚未登录)以进行身份验证并返回到同一控制器以执行剩余操作?