python获取坐标颜色_Python matplotlib:数据坐标中的位置颜色条

本文介绍如何在Python的matplotlib库中,根据数据坐标而非图形坐标来定位颜色条。通过示例代码展示了如何生成散点图,并将颜色条放置在指定的数据坐标范围内。
摘要由CSDN通过智能技术生成

我想通过指定数据坐标中的位置将颜色条放在散点图中.

以下是指定图形坐标时的工作原理示例:

import numpy as np

import matplotlib.pyplot as plt

#Generate some random data:

a = -2

b = 2

x = (b - a) * np.random.random(50) + a

y = (b - a) * np.random.random(50) + a

z = (b) * np.random.random(50)

#Do a scatter plot

fig = plt.figure()

hdl = plt.scatter(x,y,s=20,c=z,marker='o',vmin=0,vmax=2)

ax = plt.gca()

ax.set_xlim([-2,2])

ax.set_ylim([-2,2])

#Specifying figure coordinates works fine:

fig_coord = [0.2,0.8,0.25,0.05]

cbar_ax = fig.add_axes(fig_coord)

clevs = [0, 1 , 2]

cb1 = plt.colorbar(hdl, cax=cbar_ax, orientation='horizontal', ticks=clevs)

plt.show()

……好吧,不能在这里包含情节图像,因为我缺乏声誉.但上面的代码会给你一个印象….

现在问题是,如何将颜色条定位在数据坐标处,以便出现在例如:

左,下,宽,高:-1.5,1.5,1,2.25

我已经尝试了一些方法,比如确定图中的轴位置并将其转换为数据坐标,但没有成功.

非常感谢您的想法或指出我已经回答了类似的问题!

这是我做的(不是特别漂亮,但它有帮助).谢谢tcaswell!

#[lower left x, lower left y, upper right x, upper right y] of the desired colorbar:

dat_coord = [-1.5,1.5,-0.5,1.75]

#transform the two points from data coordinates to display coordinates:

tr1 = ax.transData.transform([(dat_coord[0],dat_coord[1]),(dat_coord[2],dat_coord[3])])

#create an inverse transversion from display to figure coordinates:

inv = fig.transFigure.inverted()

tr2 = inv.transform(tr1)

#left, bottom, width, height are obtained like this:

datco = [tr2[0,0], tr2[0,1], tr2[1,0]-tr2[0,0],tr2[1,1]-tr2[0,1]]

#and finally the new colorabar axes at the right position!

cbar_ax = fig.add_axes(datco)

#the rest stays the same:

clevs = [0, 1 , 2]

cb1 = plt.colorbar(hdl, cax=cbar_ax, orientation='horizontal', ticks=clevs)

plt.show()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值