在matplotlib中的方形绘图区域上绘制对数线性图

时间:2014-07-02 16:00:19

标签: python matplotlib logarithm

我想在matplotlib的方形绘图区域绘制一个对数y轴和一个线性x轴的图。我可以在正方形上绘制线性线性图和对数图,但是我使用的方法Axes.set_aspect(...)没有用于对数线性图。有一个很好的解决方法吗?


正方形上的线性线性图:

from pylab import *
x = linspace(1,10,1000)
y = sin(x)**2+0.5
plot (x,y)
ax = gca()
data_aspect = ax.get_data_ratio()
ax.set_aspect(1./data_aspect)
show()

Square linear-linear plot


广场上的对数 - 对数图:

from pylab import *
x = linspace(1,10,1000)
y = sin(x)**2+0.5
plot (x,y)
ax = gca()
ax.set_yscale("log")
ax.set_xscale("log")
xmin,xmax = ax.get_xbound()
ymin,ymax = ax.get_ybound()
data_aspect = (log(ymax)-log(ymin))/(log(xmax)-log(xmin))
ax.set_aspect(1./data_aspect)
show()

square log-log plot


但是当我尝试使用对数线性图时,我没有得到方形区域,而是一个警告

from pylab import *
x = linspace(1,10,1000)
y = sin(x)**2+0.5
plot (x,y)
ax = gca()
ax.set_yscale("log")
xmin,xmax = ax.get_xbound()
ymin,ymax = ax.get_ybound()
data_aspect = (log(ymax)-log(ymin))/(xmax-xmin)
ax.set_aspect(1./data_aspect)
show()

发出警告:

axes.py:1173: UserWarning: aspect is not supported for Axes with xscale=linear, yscale=log

not-square log-linear plot


尽管Axes.set_aspect缺乏支持,是否有一种实现平方对数线性图的好方法?

1 个答案:

答案 0 :(得分:5)

嗯,有一种解决方法。实际的轴区域(图表所在的区域,不包括外部刻度和c)可以调整为您想要的任何大小。

您可以使用ax.set_position设置绘图的相对大小和位置(图中)。为了在你的情况下使用它,我们需要一些数学:

from pylab import *

x = linspace(1,10,1000)
y = sin(x)**2+0.5
plot (x,y)
ax = gca()
ax.set_yscale("log")

# now get the figure size in real coordinates:
fig  = gcf()
fwidth = fig.get_figwidth()
fheight = fig.get_figheight()

# get the axis size and position in relative coordinates
# this gives a BBox object
bb = ax.get_position()

# calculate them into real world coordinates
axwidth = fwidth * (bb.x1 - bb.x0)
axheight = fheight * (bb.y1 - bb.y0)

# if the axis is wider than tall, then it has to be narrowe
if axwidth > axheight:
    # calculate the narrowing relative to the figure
    narrow_by = (axwidth - axheight) / fwidth
    # move bounding box edges inwards the same amount to give the correct width
    bb.x0 += narrow_by / 2
    bb.x1 -= narrow_by / 2
# else if the axis is taller than wide, make it vertically smaller
# works the same as above
elif axheight > axwidth:
    shrink_by = (axheight - axwidth) / fheight
    bb.y0 += shrink_by / 2
    bb.y1 -= shrink_by / 2

ax.set_position(bb)

show()

轻微的风格评论是import pylab通常不被使用。传说:

import matplotlib.pyplot as plt

pylab作为numpymatplotlib导入的奇怪混合,旨在简化交互式IPython的使用。 (我也使用它。)