gpt4 book ai didi

python - matplotlib pyplot 2 在同一图中使用不同轴绘制

转载 作者:太空宇宙 更新时间:2023-11-04 05:57:31 26 4
gpt4 key购买 nike

我有一个关于 matplotlib.pyplot 的小问题,我希望之前有人遇到过它。

我有包含 X、Y、e 值的数据,这些值是变量的 X、Y 测量值,e 是 Y 中测量值的误差。我需要以对数对数刻度绘制它们。

我使用 plt.errorbars 函数绘制它们,然后将 yscale 和 xscale 设置为 log,这工作正常。但我还需要在同一个图表上绘制一条线,该线需要采用线性比例。

我可以单独完成这些图,但如果可能的话,我希望将它们放在同一张图片中。你有什么想法?我正在发布我目前所做的事情。

干杯,和服

    tdlist = np.array([0.01,0.02,0.05,0.1,0.2,0.3,0.4,0.5,0.8,1,2,5,10,15,20,25,30,40,60,80,100,150,200,250,300,400])
freqlist=np.array([30,40,50,60,70,80,90,100,110,120,140,160,180,200,220,250,300,350,400,450])

filename=opts.filename

data = reader(filename)
data2 = logconv(data)

#x,y,e the data. Calculating usefull sums
x = data2[0]
y = data2[1]
e = data2[2]

xoe2 = np.sum(x/e**2)
yoe2 = np.sum(y/e**2)
xyoe2 = np.sum(x*y/e**2)
oe2 = np.sum(1/e**2)
x2oe2 = np.sum(x**2/e**2)

aslope = (xoe2*yoe2-xyoe2*oe2)/(xoe2**2-x2oe2*oe2)
binter = (xyoe2-aslope*x2oe2)/xoe2
aerr = np.sqrt(oe2/(x2oe2*oe2-xoe2**2))
berr = np.sqrt(x2oe2/(x2oe2*oe2-xoe2**2))

print('slope is ',aslope,' +- ', aerr)
print('inter is ',binter,' +- ', berr)

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax2 = fig.add_axes(ax1.get_position(), frameon=False)

ax1.errorbar(data[0],data[1],yerr=data[2],fmt='o')
ax1.set_xscale('log',basex=10)
ax1.set_yscale('log',basey=10)
ax1.set_yticks([])
ax1.set_xticks([])


ax2.plot(x,aslope*x+binter,'r')
ax2.plot(x,(aslope-aerr)*x+(binter+berr),'--')
ax2.plot(x,(aslope+aerr)*x+(binter-berr),'--')
ax2.set_xscale('linear')
ax2.set_yscale('linear')
plt.xticks(np.log10(freqlist),freqlist.astype('int'))
plt.yticks(np.log10(tdlist),tdlist.astype('float'))

plt.xlabel('Frequency (MHz)')
plt.ylabel('t_s (msec)')
fitndx1 = 'Fit slope '+"{0:.2f}".format(aslope)+u"\u00B1"+"{0:.2f}".format(aerr)
plt.legend(('Data',fitndx1))




plt.show()

按照 Molly 的建议,我设法接近了我的目标,但仍然没有达到。我正在为我正在尝试做的事情添加更多信息,这可能会澄清一些事情。

我将 ax1 设置为使用对数对数刻度的误差条图。我需要使用 errorbar 而不是 loglog plot,这样我就可以用我的观点显示错误。

我正在使用 ax2 以线性比例绘制线性拟合。

此外,我不希望 x 和 y 轴显示 10,100,1000 的 10 次方的值,但我自己的轴标签具有我想要的间距,因此我使用 plt.xticks。我尝试了 ax1.set_yticks 和 ax1.set_yticklabes 但没有成功。下面是我得到的图像。

我没有足够的声誉来发布图片,但这是上传的链接

http://postimg.org/image/uojanigab/

我的点的值应该是 x 范围 = 40 - 80 和 y 范围 = 5 -200,就像现在的拟合线一样。

最佳答案

您可以使用 figure 的 add_suplot 方法创建两个重叠轴.这是一个例子:

from matplotlib import pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax2 = fig.add_axes(ax1.get_position(), frameon=False)

ax1.loglog([1,10,100,1000],[1000,1,100,10])
ax2.plot([5,10,11,13],'r')

plt.show()

log and linear scale on the same plot

然后您可以像这样关闭线性比例图的 x 和 y 刻度:

ax2.set_xticks([])
ax2.set_yticks([])

enter image description here

关于python - matplotlib pyplot 2 在同一图中使用不同轴绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26896333/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com