一个用于多个pandas子图的颜色条

时间:2017-01-25 19:48:50

标签: python pandas matplotlib plot

我无法为我的生活弄清楚如何为多个pandas子图附加一个颜色条。几乎所有解决为多个子图放置一个颜色条的问题的其他问题都使用np数组而不是数据框来绘制。

有一个问题,One colorbar for seaborn heatmaps in subplot,似乎它可能有用,但我无法弄清楚如何将它扩展到我的案例。

有人可以帮忙吗?下面是我当前代码的示例。提前致谢!

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

# If you're using a notebook:
# %matplotlib inline

df = pd.DataFrame({"BASE": np.random.randn(10),
            "A": np.random.randn(10),
            "B": np.random.randn(10),
             "C": np.random.randn(10), 
             "D": np.random.randn(10),
            "color_col": [1,1,2,2,1,1,2,1,2,2]})




plt.figure(1, figsize = (15,15))

plt.subplot(2,2,1)
df.plot.scatter(x = "BASE", y = "A", c = df["color_col"], ax = plt.gca())

plt.subplot(2,2,2)
df.plot.scatter(x = "BASE", y = "B", c = df["color_col"], ax = plt.gca())

plt.subplot(2,2,3)
df.plot.scatter(x = "BASE", y = "C", c = df["color_col"], ax = plt.gca())

plt.subplot(2,2,4)
df.plot.scatter(x = "BASE", y = "D", c = df["color_col"], ax = plt.gca())

1 个答案:

答案 0 :(得分:2)

问题Matplotlib 2 Subplots, 1 Colorbar可能更符合您的要求。 但问题是您无法直接访问在pandas散点图中创建的映射。

这里的解决方案是使用它plt.gca().get_children()[0]从轴中提取这个可映射的(在本例中为PatchCollection),它从轴中获取第一个子艺术家。

只要所有散点图共享相同的颜色,就会保存此方法  只要轴上没有其他艺术家。

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

df = pd.DataFrame({"BASE": np.random.randn(10),
            "A": np.random.randn(10),
            "B": np.random.randn(10),
             "C": np.random.randn(10), 
             "D": np.random.randn(10),
            "color_col": np.random.randn(10)})

fig = plt.figure(1, figsize = (6,6))
plt.subplots_adjust(wspace=0.5, right=0.8, top=0.9, bottom=0.1)
for i, col in enumerate("ABCD"):
    plt.subplot(2,2,i+1)
    df.plot.scatter(x = "BASE", y = col, ax = plt.gca(), 
                    c = df["color_col"], cmap="jet", colorbar=False)

# we now take the first axes and 
# create a colorbar for it's first child (the PathCollection from scatter)
# this is save as long as all scatterplots share the same colors and
# as long as there are no other artists in the axes.
im = plt.gca().get_children()[0]
cax = fig.add_axes([0.85,0.1,0.03,0.8]) 
fig.colorbar(im, cax=cax)

plt.show()

enter image description here