加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 在matplot lib中创建inset

发布时间:2020-12-16 21:57:01 所属栏目:Python 来源:网络整理
导读:我在matplot lib中创建了一个图,我希望在该图中添加一个插图.我希望绘制的数据保存在我在其他图中使用的字典中.我在循环中找到了这个数据,然后我再次为子图运行这个循环.以下是相关部分: leg = [] colors=['red','blue']count = 0 for key in Xpr: #Xpr hol

我在matplot lib中创建了一个图,我希望在该图中添加一个插图.我希望绘制的数据保存在我在其他图中使用的字典中.我在循环中找到了这个数据,然后我再次为子图运行这个循环.以下是相关部分:

leg = []     
colors=['red','blue']
count = 0                     
for key in Xpr: #Xpr holds my data
    #skipping over what I don't want to plot
    if not key[0] == '5': continue 
    if key[1] == '0': continue
    if key[1] == 'a': continue
    leg.append(key)
    x = Xpr[key]
    y = Ypr[key] #Ypr holds the Y axis and is created when Xpr is created
    plt.scatter(x,y,color=colors[count],marker='.')
    count += 1

plt.xlabel(r'$z/mu$')
plt.ylabel(r'$rho(z)$')
plt.legend(leg)
plt.xlim(0,10)
#Now I wish to create the inset
a=plt.axes([0.7,0.7,0.8,0.8])
count = 0
for key in Xpr:
    break
    if not key[0] == '5': continue
    if key[1] == '0': continue
    if key[1] == 'a': continue
    leg.append(key)
    x = Xpr[key]
    y = Ypr[key]
    a.plot(x,color=colors[count])
    count += 1
plt.savefig('ion density 5per Un.pdf',format='pdf')

plt.cla()

奇怪的是,当我试图移动插入位置时,我仍然得到之前的插入(来自上一代代码的插件).我甚至试图在没有明显的情况下注释掉a = axes([])行.我附上了示例文件.为什么它以这种方式行事?

最佳答案
简单的答案是你应该使用plt.clf()来清除数字,而不是当前的轴.插入循环中还有一个中断,这意味着该代码都不会运行.

当你开始做比使用单轴更复杂的事情时,值得切换到使用matplotlib的OO接口.一开始可能看起来更复杂,但您不必再担心pyplot的隐藏状态.您的代码可以重写为

fig = plt.figure()
ax = fig.add_axes([.1,.1,.8,.8]) # main axes
colors=['red','blue']
for key  in Xpr: #Xpr holds my data
    #skipping over what I don't want to plot
    if not key[0] == '5': continue 
    if key[1] == '0': continue
    if key[1] == 'a': continue
    x = Xpr[key]
    y = Ypr[key] #Ypr holds the Y axis and is created when Xpr is created
    ax.scatter(x,marker='.',label=key)
    count += 1

ax.set_xlabel(r'$z/mu$')
ax.set_ylabel(r'$rho(z)$')
ax.set_xlim(0,10)
leg = ax.legend()

#Now I wish to create the inset
ax_inset=fig.add_axes([0.7,0.3,0.3])
count =0
for key  in Xpr: #Xpr holds my data
    if not key[0] == '5': continue
    if key[1] == '0': continue
    if key[1] == 'a': continue
    x = Xpr[key]
    y = Ypr[key]
    ax_inset.plot(x,label=key)
    count +=1

ax_inset.legend()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读