python - 创建一个包含打印输出和绘图的文件

标签 python pandas matplotlib

我有一个数据帧列表和一个 json 列表,我想将 df 图和 json 放入一个漂亮的文件(pdf 或 jpeg)中, 到目前为止,我添加了 json 作为绘图的标题,这对于短字符串来说效果很好(见下文),但是对于较长的 json 会出现问题,我想将它们添加为简单的打印而不是标题,有什么想法吗?

这是我所拥有的:

lodf = [pd.DataFrame([-1*x for x in range(20)]), pd.DataFrame(range(20))]
fig = plt.figure(figsize=[16,2*len(lodf)])

for i, df0 in enumerate(lodf):
    ax = fig.add_subplot(len(lodf), 1, i+1)
    df0.plot(style='.', ms=8, ax=ax)
    ax.set_ylabel("YYY")
    ax.set_title('I want this as a print out since it is a long json', wrap=True)

plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.6)
plt.savefig('just_an_example.pdf')

给出:

enter image description here

最佳答案

一种方法是使用 LaTex tabular 环境来控制换行,如下所示

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rcParams
rcParams["text.usetex"] = True

figsize = [10, 6]
plt.figure(figsize=figsize)
string = "string string string string string string string string string "
strings = [string]
for i in range(1, 6):
    strings.append(strings[i-1]+string)

plt.title(r'\begin{tabular}{p{'+str(figsize[0])+'in}} '+strings[5]+' \end{tabular}')
plt.show()

将标题包裹在图形边界处:

enter image description here

当然,这不是最简单的文本换行方式(请参阅 this answer ),但是与大多数其他方法相比,这可以更好地控制格式。例如,如果您想格式化某些代码,您可以执行以下操作

figsize = [10, 6]
plt.figure(figsize=figsize)
code = 'def function(arg1, arg2, arg3, kwarg1=None, kwarg2=None): \n\t print(arg1) '+
       '\n\t print(arg2) \n\t print(arg3)'
table = code.replace("\n", "\\\\").replace("\t", "\hspace{1cm}")
plt.title(r'\ttfamily \begin{tabular}{p{'+str(figsize[0])+'in}}'+table+'\end{tabular}')
plt.show()

这给出

enter image description here

我使用 LaTex 方法的原因是允许对字符串进行更高级的格式化 - 允许将代码格式化为任何 matplotlib 文本方法中的代码 (title()xlabel()/ylabel()text() 等)。

关于python - 创建一个包含打印输出和绘图的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59918407/

相关文章:

javascript - 我可以将 javascript 与 bottle(框架)一起使用吗?

python-2.7 - 为什么 pd.to_datetime 转换失败?

Python pandas dataframe "Don' t 想修剪值”

python - 在 Pandas 数据框中用 NaN 替换空列表

python - CMake 后在 PyCharm 中找不到模块 cv2 (OpenCV)

python - 将网球结果表(包括比赛)刮到每一行

c# - 使用 IronPython 和 .Net 的鼠标现状

python2.7 : matplotlib in jupyter notebook can't use qt

python - 在散点图中显示方向箭头

python - 为什么这个函数具有对数时间复杂度(计算一个数的 n 次方根)?