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

Mar*_*kus 2 python logarithm matplotlib

我想在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()
Run Code Online (Sandbox Code Playgroud)

方形线性线性图


广场上的对数图:

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()
Run Code Online (Sandbox Code Playgroud)

方形对数图


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

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()
Run Code Online (Sandbox Code Playgroud)

发出警告:

axes.py:1173: UserWarning: aspect is not supported for Axes with xscale=linear, yscale=log
Run Code Online (Sandbox Code Playgroud)

非平方对数线性图


尽管缺乏支持,有没有一种方法可以实现平方对数线性图Axes.set_aspect

DrV*_*DrV 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()
Run Code Online (Sandbox Code Playgroud)

一种轻微的风格评论是import pylab通常不常用的.传说:

import matplotlib.pyplot as plt
Run Code Online (Sandbox Code Playgroud)

pylab作为奇怪的混合numpymatplotlib创建,使交互式IPython使用更容易.(我也用它.)