我想在 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()
正方形上的对数对数图:
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()
但是当我用对数线性图尝试这个时,我没有得到方形区域,而是一个警告
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
尽管缺少 Axes.set_aspect
的支持,是否有实现方形对数线性图的好方法?
最佳答案
好吧,有一种解决方法。实际轴区域(绘图所在的区域,不包括外部刻度 &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
作为 numpy
和 matplotlib
导入的奇特混合体,旨在使交互式 IPython
使用更轻松。 (我也用它。)
关于python - 在 matplotlib 中的正方形绘图区域上绘制对数线性图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24535848/