Python matplotlib渲染中的紧密_布局问题

Python matplotlib渲染中的紧密_布局问题,python,matplotlib,rendering,Python,Matplotlib,Rendering,我有以下代码: import matplotlib.pyplot as plt import matplotlib from matplotlib.ticker import AutoMinorLocator import matplotlib.ticker as ticker import pylab as pl import numpy as np matplotlib.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica'

我有以下代码:

import matplotlib.pyplot as plt
import matplotlib
from matplotlib.ticker import AutoMinorLocator
import matplotlib.ticker as ticker
import pylab as pl
import numpy as np

matplotlib.rc('font',**{'family':'sans-serif','sans-serif':['Helvetica'], 'weight':'bold'})
from matplotlib.font_manager import fontManager, FontProperties
matplotlib.rcParams['mathtext.fontset'] = 'custom'
matplotlib.rcParams['mathtext.rm'] = 'Helvetica'
matplotlib.rcParams['mathtext.it'] = 'Helvetica:italic'
matplotlib.rcParams['mathtext.bf'] = 'Helvetica:bold'
font= FontProperties(weight='bold',size=18)

data = np.genfromtxt('data', names=True, dtype=None, usecols=("x", "y1", "y2", "y3")) 
x = data['x'] 
n = data['y1'] 
j = data['y2'] 
v = data['y3'] 
minorLocator = AutoMinorLocator(2)
def format():
    for axis in ['top','bottom','left','right']:
        ax.spines[axis].set_linewidth(3)

    for tick in ax.yaxis.get_ticklabels():
            tick.set_fontsize(22)
            tick.set_weight('bold')

    for tick in ax.xaxis.get_ticklabels():
            tick.set_fontsize(22)
            tick.set_weight('bold')

    ax.set_ylabel(r'$\mathrm{ \Delta{}E_{solv}^{imp}}$',fontsize=26,fontweight='bold')
    ax.tick_params(axis='x', which='both', direction='in', length=10, width=3, pad=8, top='off') 
    ax.tick_params(axis='y', which='major', direction='in', length=10, width=3, pad=8, right='off') 
    ax.tick_params(axis='y', which='minor', direction='in', length=6, width=2, right='off') 


fig = plt.figure(figsize=(9.6,12), dpi=300, linewidth=3.0)
ax = fig.add_subplot(211)

r=np.arange(1,25,1.5)
p1 = ax.bar(r,v,width=0.9,color='white',edgecolor='black', lw=1.0, align='center')
p2 = ax.bar(r,j,width=0.6,color='red',edgecolor='black', lw=1.0, align='center')
p3 = ax.bar(r,n,width=0.3,color='black',edgecolor='black', lw=1.0, align='center')

ax.set_xticks(r)
ax.set_xticklabels(x,rotation=45) 
format()
plt.axhline(y=0,linewidth=1,color='black')   
plt.axis([0.0,24.5,-0.36,0.15])
ax.yaxis.set_minor_locator(minorLocator)
pl.rc('axes',linewidth=3)
ax.xaxis.grid(True,which='major',color='gray', linestyle='--',linewidth=0.5)
ax.set_axisbelow(True)

data = np.genfromtxt('data-2', names=True, dtype=None, usecols=("x", "y1"))
x = data['x']
n = data['y1']

ax = fig.add_subplot(212)
r=np.arange(1,31,1.5)
p1 = ax.bar(r,v,width=0.9,color='red',edgecolor='black', lw=1.0, align='center')
ax.set_xticks(r)
ax.set_xticklabels(x,rotation=90) 
format()
plt.axhline(y=0,linewidth=1,color='black')   
plt.axis([0.0,30.5,-0.48,0.40])
for label in ax.xaxis.get_ticklabels():         
    label.set_horizontalalignment('center') 

ax.yaxis.set_minor_locator(minorLocator)
pl.rc('axes',linewidth=3)

ax.xaxis.grid(True,which='major',color='gray',linestyle='--',linewidth=0.5)
ax.set_axisbelow(True)   
fig.set_tight_layout(True)  #tried plt.tight_layout() also. didn't work
plt.savefig('image.png',dpi=300,format='png', orientation='landscape')
我无法保存plt.show()图形。我得到以下错误。即使删除fig.set_tight_布局(True)行,我仍然会得到相同的错误。发布这整段代码的原因是,如果我运行部分代码,我无法重现相同的错误

谢谢你的帮助

Traceback (most recent call last):
  File "image.py", line 83, in <module>
    plt.savefig('image.png',dpi=300,format='png', orientation='landscape')
  File "/usr/local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 576, in savefig
    res = fig.savefig(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py", line 1470, in savefig
    self.canvas.print_figure(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 2192, in print_figure
    **kwargs)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 513, in print_png
    FigureCanvasAgg.draw(self)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 461, in draw
    self.figure.draw(self.renderer)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/figure.py", line 1079, in draw
    func(*args)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 2092, in draw
    a.draw(renderer)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/artist.py", line 59, in draw_wrapper
    draw(artist, renderer, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/axis.py", line 1105, in draw
    renderer)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/axis.py", line 1054, in _get_tick_bboxes
    extent = tick.label1.get_window_extent(renderer)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/text.py", line 741, in get_window_extent
    bbox, info, descent = self._get_layout(self._renderer)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/text.py", line 320, in _get_layout
    ismath=ismath)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 220, in get_text_width_height_descent
    self.mathtext_parser.parse(s, self.dpi, prop)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/mathtext.py", line 3005, in parse
    box = self._parser.parse(s, font_output, fontsize, dpi)
  File "/usr/local/lib/python2.7/site-packages/matplotlib/mathtext.py", line 2339, in parse
    six.text_type(err)]))
ValueError: 
_
 ^
Expected "\" (at char 1), (line:1, col:2)
回溯(最近一次呼叫最后一次):
文件“image.py”,第83行,在
plt.savefig('image.png',dpi=300,format='png',orientation='scape')
savefig中的文件“/usr/local/lib/python2.7/site packages/matplotlib/pyplot.py”,第576行
res=图savefig(*args,**kwargs)
savefig中的文件“/usr/local/lib/python2.7/site packages/matplotlib/figure.py”,第1470行
self.canvas.print_图(*args,**kwargs)
文件“/usr/local/lib/python2.7/site packages/matplotlib/backend_base.py”,第2192行,如图所示
**kwargs)
文件“/usr/local/lib/python2.7/site packages/matplotlib/backends/backend_agg.py”,第513行,打印为png
图CAVASAGG.draw(自绘制)
文件“/usr/local/lib/python2.7/site packages/matplotlib/backends/backend_agg.py”,绘图中第461行
self.figure.draw(self.renderer)
文件“/usr/local/lib/python2.7/site packages/matplotlib/artist.py”,第59行,在draw_包装中
绘制(艺术家、渲染器、*args、**kwargs)
文件“/usr/local/lib/python2.7/site packages/matplotlib/figure.py”,第1079行,在绘图中
func(*args)
文件“/usr/local/lib/python2.7/site packages/matplotlib/artist.py”,第59行,在draw_包装中
绘制(艺术家、渲染器、*args、**kwargs)
文件“/usr/local/lib/python2.7/site packages/matplotlib/axes/_base.py”,绘图中第2092行
a、 绘制(渲染器)
文件“/usr/local/lib/python2.7/site packages/matplotlib/artist.py”,第59行,在draw_包装中
绘制(艺术家、渲染器、*args、**kwargs)
文件“/usr/local/lib/python2.7/site packages/matplotlib/axis.py”,第1105行,在绘图中
渲染器)
文件“/usr/local/lib/python2.7/site packages/matplotlib/axis.py”,第1054行,在“获取”框中
范围=勾选.label1.get\u window\u范围(渲染器)
文件“/usr/local/lib/python2.7/site packages/matplotlib/text.py”,第741行,在get_窗口中
bbox,info,下降=self.\u获取布局(self.\u渲染器)
文件“/usr/local/lib/python2.7/site packages/matplotlib/text.py”,第320行,在get布局中
ismath=ismath)
文件“/usr/local/lib/python2.7/site packages/matplotlib/backends/backend\u agg.py”,第220行,在get\u text\u width\u height\u中
self.mathtext_parser.parse(s,self.dpi,prop)
文件“/usr/local/lib/python2.7/site packages/matplotlib/mathtext.py”,第3005行,在parse中
box=self.\u parser.parse(s,font\u输出,fontsize,dpi)
文件“/usr/local/lib/python2.7/site packages/matplotlib/mathtext.py”,第2339行,在parse中
六、文本(类型(错误)])
值错误:
_
^
应为“\”(在字符1处),(第1行,第2列)

这实际上是一些与数学格式相关的问题,尽管不是在ylabel中。我不知道为什么,但重新输入所有的列表元素(包含几个$A_A$)再次奏效。

看起来可能是您的
ylabel
。尝试删除所有的数学格式,看看它是否有效-至少可以缩小问题的范围