简体   繁体   中英

Align a matplotlib figure to the text in LaTeX

I am trying to create a matplotlib figure in LaTeX that is aligned perfectly to the text. This is my code that I took from here .

I adjusted some parameters, but the concept remains the same.

In Python:

import pylab
from pylab import arange,pi,sin,cos,sqrt
fig_width_pt = 430.00462 #246.0 # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27               # Convert pt to inch
golden_mean = (sqrt(5)-1.0)/2.0         # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt  # width in inches
fig_height = fig_width*golden_mean      # height in inches
fig_size =  [fig_width,fig_height]
params = {'backend': 'ps',
          'axes.labelsize': 12, # 10
          'text.fontsize': 12, # 10
          'legend.fontsize': 12, # 10
          'xtick.labelsize': 8, # 8
          'ytick.labelsize': 8, # 8
          'text.usetex': True,
          'figure.figsize': fig_size}
pylab.rcParams.update(params)
# Generate data
x = pylab.arange(-2*pi,2*pi,0.01)
y1 = sin(x)
y2 = cos(x)
# Plot data
pylab.figure(1)
pylab.clf()
pylab.axes([0.125,0.2,0.95-0.125,0.95-0.2])
pylab.plot(x,y1,'g:',label='$\sin(x)$')
pylab.plot(x,y2,'-b',label='$\cos(x)$')
pylab.xlabel('$x$ (radians)')
pylab.ylabel('$y$')
pylab.legend()
pylab.savefig('fig1.pdf')

In LaTeX:

\begin{figure}
\begin{center}
  \includegraphics[width=\columnwidth]{fig1.pdf}
\end{center}
\end{figure}

My LaTeX file then renders this:

我的输出

Now, actually to align it perfectly, in my understanding, It should be more like this: 什么必须改变

Unfortunately, I did not find out how to

  • set the rectangle's width in which grahpic is drawn

  • get the ylabel's width to subtract it from the total figsize

If I adjust pylab.axes() , I can change the position of the graph inside the pdf, but moving it too far to the left or to the right then cuts of parts of the picture, as the adjustment is performed inside the pdf itself, not in LaTeX. Also, I do not know how much it should be moved as the ylabel's width is unknown.

Have you got any suggestions?

Here is code that can get the position informations:

fig = pylab.gcf()
ax = pylab.gca()
print fig.bbox.bounds
print ax.bbox.bounds
ylabel = ax.yaxis.label
print ylabel.get_transform().transform(l.get_position())

print ylabel.get_window_extent()

Also try to create the axes by:

pylab.axes([0.125,0.2,0.75,0.95-0.2])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM