在pandas/matplotlib中获取散点图的Colorbar实例 [英] Getting Colorbar instance of scatter plot in pandas/matplotlib
问题描述
如何获取由pandas.DataFrame.plot创建的图的内部创建的颜色栏实例?
How do I get the internally created colorbar instance of a plot created by pandas.DataFrame.plot?
以下是生成彩色散点图的示例:
Here is an example for generating a colored scatter plot:
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()
这给了我一个这样的数字:
which gives me a figure like this:
如何获取颜色条实例以进行操作,例如更改标签或设置刻度线?
How do I get the colorbar instance in order to manipulate it, for instance for changing the label or setting the ticks?
推荐答案
pandas
不会返回颜色条的轴,因此我们必须找到它:
pandas
does not return the axis for the colorbar, therefore we have to locate it:
首先,让我们获取figure
实例:即,使用plt.gcf()
1st, let's get the figure
instance: i.e., use plt.gcf()
In [61]:
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] )
f = plt.gcf()
2,该图形有多少个轴?
2, how many axes does this figure have?
In [62]:
f.get_axes()
Out[62]:
[<matplotlib.axes._subplots.AxesSubplot at 0x120a4d450>,
<matplotlib.axes._subplots.AxesSubplot at 0x120ad0050>]
3,第一个轴(即创建的第一个轴)包含绘图
3, The first axes (that is, the first one created), contains the plot
In [63]:
ax
Out[63]:
<matplotlib.axes._subplots.AxesSubplot at 0x120a4d450>
4,因此,第二个轴是颜色栏轴
4, Therefore, the second axis is the colorbar axes
In [64]:
cax = f.get_axes()[1]
#and we can modify it, i.e.:
cax.set_ylabel('test')
这篇关于在pandas/matplotlib中获取散点图的Colorbar实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!