一根彩条可显示多个 pandas 子图 [英] One colorbar for multiple pandas subplots
问题描述
我一生都无法弄清楚如何为多个熊猫子图附加一个颜色条.解决所有为多个子图放置一个颜色条的问题的几乎所有其他问题都使用np数组而不是数据帧来绘制.
有一个问题,
I cannot for the life of me figure out how to attach one colorbar for multiple pandas subplots. Almost all the other questions that resolve the issue of putting one colorbar for multiple subplots use np arrays, not dataframes, to plot.
There is one question, One colorbar for seaborn heatmaps in subplot, which seems like it could be useful, however I could not figure out how to extend it to my case.
Could anyone help? Below is an example of my current code. Thanks in advance!
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())
The question Matplotlib 2 Subplots, 1 Colorbar is probably more what you are looking for. The problem is however that you do not directly have access to the mappable that is created in the pandas scatter plot.
The solution here would be to distill this mappable (in this case a PatchCollection) from the axes using it plt.gca().get_children()[0]
, which takes the first child artist from the axes.
This method is save as long as all scatterplots share the same colors and as long as there are no other artists in the axes.
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()
这篇关于一根彩条可显示多个 pandas 子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!