如何从现有的 matplotlib 散点图中检索颜色条

问题描述 投票:0回答:1

我正在尝试为一篇论文创建一个图形,该论文复合了我以 pickle 格式保存的以前的 matplotlib 图形。

为此,我使用了

get_offsets()
命令,它允许我检索散点图的点,并使用
get_facecolor()
来获取点的颜色。

代码:

### Loading my figure (visible in the enclosed picture)
with open('Figures paper/Individual spectra figures/Spectra_1000_GALL_chunk_0.pickle', 'rb') as fl:
    ax1 = pickle.load(fl)

### Getting the plot features
xd = axp.collections[0].get_offsets()[:,0]
yd = axp.collections[0].get_offsets()[:,1]
cd = axp.collections[0].get_facecolor()

ax.scatter(xd,yd, s=ar,c=cd ,alpha=0.8)

然后我可以在子面板中绘制我想要的新复合图形的点。但是,我的初始绘图的颜色条没有出现,并且我不知道如何检索它以将其包含在新绘图中。

我尝试使用从散点图中提取的数据创建一个新的颜色条,但这是不可能的,因为

.collections[0].get_facecolor()
只获取颜色的值,而不是生成它们的原始变量。

知道如何做吗?

python matplotlib colorbar
1个回答
0
投票

这是腌制颜色条的字面检索——如果您最初腌制了整个图形,这应该适用:

"""
============
Unpickle a colorbar
============

To  answer https://stackoverflow.com/questions/78088551/how-to-retrieve-a-colorbar-from-an-already-existing-matplotlib-scatter-figure

Started with https://matplotlib.org/stable/_downloads/bfeb934bd7e87a776c31ca73c7218c9e/scatter.py
"""
import matplotlib.pyplot as plt
import numpy as np
import pickle

# Fixing random state for reproducibility
np.random.seed(19680802)

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
sizes = (30 * np.random.rand(N))**2  # 0 to 15 point radii
fig, ax = plt.subplots()
scatter = ax.scatter(x, y, s=sizes, c=colors, alpha=0.5)
fig.colorbar(scatter, ax=ax)
fig.suptitle("Prepickle")
fig.savefig("unpickle_colorbar_before_pickling.png")
#plt.show() # pklsc.show() at end DOES NOT WORK if this line is uncommented?

with open("unpickle_colorbar.pkl", "wb") as f:
    pickle.dump(fig, f)

with open("unpickle_colorbar.pkl", "rb") as f:
    pklsc = pickle.load(f)

plt.figure(pklsc) 
pklsc.suptitle("Unpickled!", size=14)
pklsc.savefig("unpickle_colorbar_without_editing.png")
#If we stop here, we get the original fig, with colorbar 

# now want to reuse the scatterplot and still have the colorbar 
pklsc.suptitle("Edited the pickle", size=14)
#maybe we only want half the original points?

oldsc = pklsc.axes[0].collections[0]

# extract locations and sizes
xd = oldsc.get_offsets()[:,0]
yd = oldsc.get_offsets()[:,1]
sd = oldsc.get_sizes()
cd = oldsc.get_facecolor()

#hide what we had, but only in the scatterplot
pklsc.axes[0].clear()

#replot
M = int(N/2)
pklsc.axes[0].scatter(xd[:M], yd[:M], s=sd[:M], c=cd[:M], alpha = 0.5)
pklsc.savefig("unpickle_colorbar_after_editing.png")
#pklsc.show() 

以及剧情的三种状态:

© www.soinside.com 2019 - 2024. All rights reserved.