通过熊猫绘图界面使用颜色栏分组散点图

时间:2019-01-08 14:54:59

标签: python pandas matplotlib plot

当我从熊猫中绘制分组的散点图时(如documentation中所述),其中第二组需要包含颜色条,我得到一个错误TypeError: You must first set_array for mappable

除了different questions for ungrouped scatter plots之外,其他原因是因为cmap仅在c是浮点数数组的情况下使用。但是独立运行时效果很好,并且在创建两个轴对象之间不会处理数据。

这是我正在使用的代码:

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

df = pd.DataFrame(np.random.rand(100, 5), columns=['A', 'B', 'C', 'D', 'E'])

# this works stand-alone
#df.plot(kind='scatter', x='A', y='B', c='C', cmap='Blues')

# why does this break?
ax = df.plot(kind='scatter', x='D', y='E', color='red', label='Other group')
df.plot(kind='scatter', x='A', y='B', c='C', cmap='Blues', ax=ax)
plt.show()

两个组都应在一个图中显示。请注意,对我来说重要的是在将A,B和C绘制在列D和E之前,先在列D和E上绘制,因此后者需要在第二个图中。反之亦然,但按我的要求,它会中断。

有人知道如何解决此问题并获得所需的结果吗?

谢谢!

2 个答案:

答案 0 :(得分:2)

似乎熊猫对内部制作颜色条感到困惑。不过,您始终可以使用matplotlib创建颜色栏。

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

df = pd.DataFrame(np.random.rand(100, 5), columns=['A', 'B', 'C', 'D', 'E'])

ax = df.plot(kind='scatter', x='D', y='E', color='red', label='Other group')
df.plot(kind='scatter', x='A', y='B', c='C', cmap='Blues', ax=ax, colorbar=False)
ax.figure.colorbar(ax.collections[1])   # Note the index 1, which stands
                                        # for second scatter in the axes.
plt.show()

enter image description here

答案 1 :(得分:1)

反转绘图顺序。我认为颜色条变得困惑于要应用哪个图表。因此,我们尝试先用颜色条绘制图,然后在顶部应用红色散点图。

df = pd.DataFrame(np.random.rand(100, 5), columns=['A', 'B', 'C', 'D', 'E'])

# this works stand-alone
#df.plot(kind='scatter', x='A', y='B', c='C', cmap='Blues')

# why does this break?
# ax = df.plot(kind='scatter', x='D', y='E', color='red', abel='Other group')
ax = df.plot(kind='scatter', x='A', y='B', c='C', cmap='Blues', zorder=10)
df.plot(kind='scatter', x='D', y='E', color='red', label='Other group', ax=ax, zorder=1)
plt.show()

输出:

enter image description here

使用zorder

enter image description here

相关问题