我有一个奇怪的问题。使用 IPython Notebook,我使用 pandas 和 matplotlib 创建了一个相当广泛的脚本来创建许多图表。 当我的修补完成后,我将代码复制(并清理)到一个独立的 python 脚本中(这样我就可以将它推送到 svn 中,我的论文合著者也可以创建图表)。
为了方便起见,我再次将独立的 python 脚本导入到笔记本中,并创建了一些图表:
import create_charts as cc
df = cc.read_csv_files("./data")
cc.chart_1(df, 'fig_chart1.pdf')
...
奇怪的是,我使用上述方法获得的 .pdf 文件与我从 Windows 7 终端运行独立 python 脚本时获得的 .pdf 文件略有不同。最显着的区别是在特定图表中,图例位于上角而不是下角。但也有其他小差异(边界框大小、字体似乎略有不同)
这可能是什么原因。我该如何排除故障?
(我已经关闭我的笔记本并重新启动它,重新导入我的 create_charts
脚本并排除任何未保存的更改)
我的终端报告我正在使用 Python 2.7.2 和 pip freeze | grep ipython
报告 ipython 0.13.1
最佳答案
为了完成 Joe 的回答,内联后端 (IPython/kernel/zmq/pylab/backend_inline.py) 有一些默认的 matplotlib 参数:
# The typical default figure size is too large for inline use,
# so we shrink the figure size to 6x4, and tweak fonts to
# make that fit.
rc = Dict({'figure.figsize': (6.0,4.0),
# play nicely with white background in the Qt and notebook frontend
'figure.facecolor': 'white',
'figure.edgecolor': 'white',
# 12pt labels get cutoff on 6x4 logplots, so use 10pt.
'font.size': 10,
# 72 dpi matches SVG/qtconsole
# this only affects PNG export, as SVG has no dpi setting
'savefig.dpi': 72,
# 10pt still needs a little more room on the xlabel:
'figure.subplot.bottom' : .125
}, config=True,
help="""Subset of matplotlib rcParams that should be different for the
inline backend."""
)
这个不是很明显,大家可以通过c.InlineBackend.rc
在config中设置。
[编辑] 关于可配置性的精确信息。
IPython 的特点是大多数类都具有可以配置默认值的属性。这些通常被称为 Configurable
(大写 C),这些属性可以很容易地在代码中识别,因为它们在 __init__
之前这样声明:
property = A_Type( <default_value>, config=True , help="a string")
你可以覆盖 IPython 配置文件中的那些属性(哪个取决于你想做什么)
c.ClassName.propertie_name = value
这里是你可以做的字典
#put your favorite matplotlib config here.
c.InlineBackend.rc = {'figure.facecolor': 'black'}
我猜一个空的字典将允许内联后端使用 matplotlib 默认值。
关于python - 为什么从 ipython notebook 生成的 matplotlib 图与终端版本略有不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16905028/