在pandas/matplotlib中获取散点图的Colorbar实例

在pandas/matplotlib中获取散点图的Colorbar实例,pandas,matplotlib,plot,Pandas,Matplotlib,Plot,如何获取pandas.DataFrame.plot创建的绘图的内部创建的colorbar实例 以下是生成彩色散点图的示例: import matplotlib.pyplot as plt import pandas as pd import numpy as np import itertools as it # [ (0,0), (0,1), ..., (9,9) ] xy_positions = list( it.product( range(10), range(10) ) ) df

如何获取pandas.DataFrame.plot创建的绘图的内部创建的colorbar实例

以下是生成彩色散点图的示例:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import itertools as it

# [ (0,0), (0,1), ..., (9,9) ]
xy_positions = list( it.product( range(10), range(10) ) )

df = pd.DataFrame( xy_positions, columns=['x','y'] )

# draw 100 floats
df['score'] = np.random.random( 100 )

ax = df.plot( kind='scatter',
              x='x',
              y='y',
              c='score',
              s=500)
ax.set_xlim( [-0.5,9.5] )
ax.set_ylim( [-0.5,9.5] )

plt.show()
这给了我一个这样的数字:


如何获取colorbar实例以对其进行操作,例如更改标签或设置刻度?

虽然不完全相同,但您可以使用matplotlib进行打印:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import itertools as it

# [ (0,0), (0,1), ..., (9,9) ]
xy_positions = list( it.product( range(10), range(10) ) )

df = pd.DataFrame( xy_positions, columns=['x','y'] )

# draw 100 floats
df['score'] = np.random.random( 100 )

fig = plt.figure()
ax = fig.add_subplot(111)

s = ax.scatter(df.x, df.y, c=df.score, s=500)
cb = plt.colorbar(s)
cb.set_label('desired_label')

ax.set_xlim( [-0.5,9.5] )
ax.set_ylim( [-0.5,9.5] )

plt.show()

pandas
不返回颜色条的轴,因此我们必须找到它:

首先,让我们获得
实例:即使用
plt.gcf()

2,这个数字有多少轴

In [62]:

f.get_axes()
Out[62]:
[<matplotlib.axes._subplots.AxesSubplot at 0x120a4d450>,
 <matplotlib.axes._subplots.AxesSubplot at 0x120ad0050>]

好的,这给了我颜色条可能所在的轴。但是我怎么能确定这是正确的轴呢?我知道在我的设置中,轴列表中的第二个是我的颜色条。我不认为当你有一个包含更多轴的复杂图形(而不是在这种情况下只有2个)时,有一个简单的方法来识别颜色条轴。您可以通过检查轴是否包含
matplotlib.collections.QuadMesh
作为其子项之一(colorbar轴将包含它)来识别colorbar轴,这是颜色渐变。但是,这是一种不安全的黑客行为,因为
matplotlib.collections.QuadMesh
也可能出现在其他类型的绘图中。因此,我认为最好弄清楚轴的创建顺序,并以这种方式选择颜色条轴(轴)。最好的答案是指定如何设置刻度。此时,调用cax.set_yticks(i)将生成一个警告,而不是设置刻度,因此答案不包括问题中提出的具体挑战。是的,这也是可能的,但它失去了直接使用数据帧的优点。也许。。。但是
ax=df.plot(kind='scatter',x='x',y='y',c='score',s=500)
真的比
s=ax.scatter(df.x,df.y,c=df.score,s=500)更直接吗?我想我更喜欢这样,而不是四处寻找正确的轴;-)直接使用matplotlib可能有更多的优势,尤其是如果以后要使用和修改轴。
In [62]:

f.get_axes()
Out[62]:
[<matplotlib.axes._subplots.AxesSubplot at 0x120a4d450>,
 <matplotlib.axes._subplots.AxesSubplot at 0x120ad0050>]
In [63]:

ax
Out[63]:
<matplotlib.axes._subplots.AxesSubplot at 0x120a4d450>
In [64]:

cax = f.get_axes()[1]
#and we can modify it, i.e.:
cax.set_ylabel('test')