[英]One colorbar for multiple pandas subplots
我一生都無法弄清楚如何為多個熊貓子圖附加一個顏色條。 解決為多個子圖放置一個顏色條的問題的幾乎所有其他問題都使用 np 數組而不是數據框來繪制。
有一個問題, 一個用於 subplot 中 seaborn heatmaps 的顏色條,這似乎很有用,但是我不知道如何將其擴展到我的情況。
有人可以幫忙嗎? 下面是我當前代碼的示例。 提前致謝!
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())
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()
這里有幾顆瞄准目標的石頭。 我很確定至少還有一種方法存在(使用 GridSpec 與下面概述的不同),但我喜歡后兩種。
1.您可以簡單地選擇何時繪制顏色條與不繪制顏色條,只要您不關心是否修剪了一個子圖以為顏色條騰出空間。
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,axis = plt.subplots(nrows=1,ncols=4,figsize=(18,6))
for i, col in enumerate("ABCD"):
ax = axis[i]
df.plot.scatter(ax=ax, x = "BASE", y = col, c = df["color_col"], s = 55, cmap="jet", colorbar=(i==len("ABCD")-1))
fig.tight_layout()
plt.show()
2.如果你真的想要 2X2 網格,並且所有子圖必須是相同的大小,你可以試試這個。 我喜歡第一個答案,不必在特定位置放置顏色條。 我寧願繪制我想要的所有東西,使用現有的 tiny_layout() 功能,然后添加一個顏色條。 我保留的唯一神奇數字是 figsize。
fig,axes = plt.subplots(2,2, figsize = (9,4))
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)})
for i, col in enumerate("ABCD"):
ax = axes[i/2][i%2]
im = df.plot.scatter(x = "BASE", y = col, ax = ax, s = 35,
c = df["color_col"], cmap="jet", colorbar=False)
fig.tight_layout()
# Note: since colorbar is manu`enter code here`ally added, tight_layout must be called before
# rendering colorbar
plt.colorbar(plt.gca().get_children()[0], ax=axes.ravel().tolist())
3.另一種方法是使用 gridspec 作為 suplots 構造函數的參數:
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.gridspec as gridspec
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)})
nrows,ncols = 2,2
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, sharex='col', sharey=False,
gridspec_kw={'width_ratios': [1, 1,0.1]},
figsize=(7, 4))
for i, col in enumerate("ABCD"):
ax = axes[i/(ncols)][i%(ncols)]
im = df.plot.scatter(x = "BASE", y = col, ax = ax, s = 35
,c = df["color_col"], cmap="jet", colorbar=False)
fig.tight_layout()
cax,kw = mpl.colorbar.make_axes([ax for ax in axes.flat])
plt.colorbar(axes[0][0].get_children()[0], cax=cax, **kw)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.