简体   繁体   English

两个 Matplotlib 颜色条具有不同(条件)标准化颜色图,用于一个散点 plot?

[英]Two Matplotlib Colorbars with different (conditional) normalized colormaps for one scatter plot?

I have a dataset of 5 columns: a,b,c,d,e.我有一个 5 列的数据集:a,b,c,d,e。 where the data type of b is str , and the others contain floats .其中 b 的数据类型是str ,其他包含floats The scatter axes are the columns a and e for x and y, respectively.散点轴分别是 x 和 y 的列 a 和 e。 The normalized colormap is based on the column e.标准化颜色图基于 e 列。

I want to add two colorbars where the filling colormap is the same as in the scatter plot (of course,).我想添加两个颜色条,其中填充颜色图与散点图 plot 相同(当然,)。 but the numerical ticks are based on the columns c and d, In one of my attempts, I tried to create two figures.但数字刻度基于 c 和 d 列,在我的一次尝试中,我尝试创建两个数字。 but forcing the first colorbar to take its values from the second figure.但强制第一个颜色条从第二个图中获取其值。 But it didn't work.但它没有用。

My best attempts is the code below, which generates the attached image.我最好的尝试是下面的代码,它会生成附加的图像。 (based on the data below) The code takes the data to plot the regular colorbar, and runs the same block again for the second colorbar, where the markers's surface (in the second time) is 0 (which is funny ;) ) EDIT I tied to add a third loop. (基于下面的数据)代码将数据带到 plot 常规颜色条,并为第二个颜色条再次运行相同的块,其中标记的表面(第二次)为 0(这很有趣;) )编辑 I绑添加第三个循环。 thus: one real loop for column e, and two fake loops with marker surface is 0 for the colorbars from the c and d data.因此:e 列的一个真实循环,以及来自 c 和 d 数据的颜色条的两个带有标记表面的假循环为 0。 (see second code block), now the markers filling is not correct. (见第二个代码块),现在标记填充不正确。

ie: 1/I need to normalize two colorbars from two different columns, but normalize the filling of the markers using one column.即:1/我需要对来自两个不同列的两个颜色条进行归一化,但使用一列对标记的填充进行归一化。 2/ I wanna invert the second colorbar axis for clarity. 2/ 为了清晰起见,我想反转第二个颜色条轴。 (as if it has a reverse normalized colormap) (好像它有一个反向归一化的颜色图)

[EDIT]: To invert the second colorbar add _r to cmap in the second loop: [编辑]:要反转第二个颜色条,在第二个循环中将 _r 添加到 cmap:

Thanks everyone !感谢大家 !

Code 1代码 1

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()

a,b,c,d,e = np.loadtxt('test.txt', delimiter='\t', unpack=True, 
skiprows=1, dtype=str)

a = a.astype(np.float64)
c = c.astype(np.float64)
d = d.astype(np.float64)
e = e.astype(np.float64)
b = list(b)
#####################################################
# for c
norm = mpl.colors.Normalize(vmin=c.min(), vmax=c.max())
cmap = mpl.cm.ScalarMappable(norm=norm, cmap=mpl.cm.Reds)
cmap.set_array([])
# for d
norm2 = mpl.colors.Normalize(vmin=d.min(), vmax=d.max())
cmap2 = mpl.cm.ScalarMappable(norm=norm2, cmap=mpl.cm.Reds)
cmap2.set_array([])
# real
for i in range(len(b)):
    if b[i] == 'alpha':
        sc = ax.scatter(a[i], e[i], marker='o', edgecolors='black', 
alpha=0.8, s=120, c=e[i], norm=norm,
                        cmap='Reds'
                        )
    if b[i] == 'beta':
        sc = ax.scatter(a[i], e[i], marker='d', edgecolors='black', 
alpha=0.8, s=120, c=e[i], norm=norm,
                        cmap='Reds'
                        )
# fake
for i in range(len(b)):
    if b[i] == 'alpha':
        sc1 = ax.scatter(a[i], e[i], marker=',', edgecolors='black', 
alpha=0.8, s=0, c=e[i], norm=norm2,
                         cmap='Reds'
                         )
    if b[i] == 'beta':
        sc1 = ax.scatter(a[i], e[i], marker=',', edgecolors='black', 
alpha=0.8, s=0, c=e[i], norm=norm2,
                         cmap='Reds'
                         )
years_ax = np.linspace(2000, 2021, 21, endpoint=True, dtype=int)
ax.set_xticks(years_ax)
plt.xticks(rotation=45)  # Rotates X-Axis Ticks by 45-degrees

plt.grid(True, which="both", ls="-", alpha=0.1)
plt.xlabel('Years', fontsize=14)
plt.ylabel('e', fontsize=14)
ax.tick_params(axis='both', which='major', labelsize=14)

divider = make_axes_locatable(ax)
cba = divider.new_vertical(size='5%', pad=0.5)
cbb = divider.new_vertical(size='5%', pad=0.5)

fig.add_axes(cba)
fig.add_axes(cbb)

# add colorbar #1
cba = plt.colorbar(sc, cax=cba, orientation='horizontal')
ax.xaxis.set_ticks_position('default')
cba.ax.xaxis.set_ticks_position('top')
# add colorbar #2
cbb = plt.colorbar(sc1, cax=cbb, orientation='horizontal')
cbb.ax.invert_yaxis()
ax.xaxis.set_ticks_position('default')
cbb.ax.xaxis.set_ticks_position('top')

plt.show()

Code 2:代码 2:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()

a,b,c,d,e = np.loadtxt('test.txt', delimiter='\t', unpack=True, 
skiprows=1, dtype=str)

a = a.astype(np.float64)
c = c.astype(np.float64)
d = d.astype(np.float64)
e = e.astype(np.float64)
b = list(b)
#####################################################
# for e
norme = mpl.colors.Normalize(vmin=e.min(), vmax=e.max())
cmape = mpl.cm.ScalarMappable(norm=norme, cmap=mpl.cm.Reds)
cmape.set_array([])
# for c
normc = mpl.colors.Normalize(vmin=c.min(), vmax=c.max())
cmapc = mpl.cm.ScalarMappable(norm=normc, cmap=mpl.cm.Reds)
cmapc.set_array([])
# for d
normd = mpl.colors.Normalize(vmin=e.min(), vmax=e.max())
cmapd = mpl.cm.ScalarMappable(norm=normd, cmap=mpl.cm.Reds_r)
cmapd.set_array([])
# real
for i in range(len(b)):
    if b[i] == 'alpha':
        sc = ax.scatter(a[i], e[i], marker='o', edgecolors='black', 
alpha=0.8, s=120, c=e[i], norm=norme,
                        cmap='Reds'
                        )
    if b[i] == 'beta':
        sc = ax.scatter(a[i], e[i], marker='d', edgecolors='black', 
alpha=0.8, s=120, c=e[i], norm=norme,
                        cmap='Reds'
                        )
# fake for c
for i in range(len(b)):
    if b[i] == 'alpha':
        sc = ax.scatter(a[i], e[i], marker='o', edgecolors='black', 
alpha=0.8, s=0, c=e[i], norm=normc,
                        cmap='Reds'
                        )
    if b[i] == 'beta':
        sc = ax.scatter(a[i], e[i], marker='d', edgecolors='black', 
alpha=0.8, s=0, c=e[i], norm=normc,
                        cmap='Reds'
                        )
# fake for d
for i in range(len(b)):
    if b[i] == 'alpha':
        sc1 = ax.scatter(a[i], e[i], marker=',', edgecolors='black', 
alpha=0.8, s=0, c=e[i], norm=normd,
                         cmap='Reds_r'
                         )
    if b[i] == 'beta':
        sc1 = ax.scatter(a[i], e[i], marker=',', edgecolors='black', 
alpha=0.8, s=0, c=e[i], norm=normd,
                         cmap='Reds_r'
                         )
years_ax = np.linspace(2000, 2021, 21, endpoint=True, dtype=int)
ax.set_xticks(years_ax)
plt.xticks(rotation=45)  # Rotates X-Axis Ticks by 45-degrees

plt.grid(True, which="both", ls="-", alpha=0.1)
plt.xlabel('Years', fontsize=14)
plt.ylabel('e', fontsize=14)
ax.tick_params(axis='both', which='major', labelsize=14)

divider = make_axes_locatable(ax)
cba = divider.new_vertical(size='5%', pad=0.5)
cbb = divider.new_vertical(size='5%', pad=0.5)

fig.add_axes(cba)
fig.add_axes(cbb)

# add colorbar #1
cba = plt.colorbar(sc, cax=cba, orientation='horizontal')
ax.xaxis.set_ticks_position('default')
cba.ax.xaxis.set_ticks_position('top')
# add colorbar #2
cbb = plt.colorbar(sc1, cax=cbb, orientation='horizontal')
cbb.ax.invert_yaxis()
ax.xaxis.set_ticks_position('default')
cbb.ax.xaxis.set_ticks_position('top')
plt.show()

Result: result image结果:结果图像

Result from third attempt (with three loops, and corrected inverted bars)第三次尝试的结果(三个循环和更正的倒线)

second attempt第二次尝试

data sample -small-:数据样本-小-:

a   b   c   d   e
2013    alpha   21.8    47  101.3302752
2013    alpha   5   23  105.8
2009    alpha   38  58  88.52631579
2009    alpha   47  77  126.1489362
2009    alpha   188 55  16.09042553
2009    alpha   267 77  22.20599251
2019    alpha   1.67    10  59.88023952
2020    alpha   31.5    57  103.1428571
2013    beta    19  50  131.5789474
2013    beta    26.8    62.5    145.755597
2013    beta    54.5    95  165.5963303
2013    beta    120.1   123 125.970025
2013    beta    147.6   137.5   128.0911247
2007    alpha   14.5    14.5    14.5
2007    alpha   28.7    28  27.31707317
2007    alpha   42.5    40  37.64705882

[Solved] Using two figures, where the second figure colorbar is just plotted in the second as follows: [已解决] 使用两个图形,其中第二个图形颜色条仅绘制在第二个图形中,如下所示:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()
fig2, ax2 = plt.subplots()

a,b,c,d,e = np.loadtxt('test.txt', delimiter='\t', unpack=True, skiprows=1, dtype=str)

a = a.astype(np.float64)
c = c.astype(np.float64)
d = d.astype(np.float64)
e = e.astype(np.float64)
b = list(b)
#####################################################
# for e
norme = mpl.colors.Normalize(vmin=e.min(), vmax=e.max())
cmape = mpl.cm.ScalarMappable(norm=norme, cmap=mpl.cm.Reds)
cmape.set_array([])
# for c
normc = mpl.colors.Normalize(vmin=c.min(), vmax=c.max())
cmapc = mpl.cm.ScalarMappable(norm=normc, cmap=mpl.cm.Reds)
cmapc.set_array([])
# for d
normd = mpl.colors.Normalize(vmin=d.min(), vmax=d.max())
cmapd = mpl.cm.ScalarMappable(norm=normd, cmap=mpl.cm.Reds_r)
cmapd.set_array([])
# real
for i in range(len(b)):
    if b[i] == 'alpha':
        sc = ax.scatter(a[i], e[i], marker='o', edgecolors='black', alpha=0.8, s=120, c=c[i], norm=normc,
                        cmap='Reds'
                        )
    if b[i] == 'beta':
        sc = ax.scatter(a[i], e[i], marker='d', edgecolors='black', alpha=0.8, s=120, c=c[i], norm=normc,
                        cmap='Reds'
                        )
# fake for c
for i in range(len(b)):
    if b[i] == 'alpha':
        sc = ax.scatter(a[i], e[i], marker='o', edgecolors='black', alpha=0.8, s=0, c=e[i], norm=normc,
                        cmap='Reds'
                        )
    if b[i] == 'beta':
        sc = ax.scatter(a[i], e[i], marker='d', edgecolors='black', alpha=0.8, s=0, c=e[i], norm=normc,
                        cmap='Reds'
                        )
# # fake for d
for i in range(len(b)):
    if b[i] == 'alpha':
        sc1 = ax2.scatter(a[i], e[i], marker=',', edgecolors='black', alpha=0.8, s=100,c=d[i], norm=normd,
                         cmap='Reds_r'
                         )
    if b[i] == 'beta':
        sc1 = ax2.scatter(a[i], e[i], marker=',', edgecolors='black', alpha=0.8, s=100,c=d[i], norm=normd,
                         cmap='Reds_r'
                         )
years_ax = np.linspace(2000, 2021, 21, endpoint=True, dtype=int)
ax.set_xticks(years_ax)
plt.xticks(rotation=45)  # Rotates X-Axis Ticks by 45-degrees

plt.grid(True, which="both", ls="-", alpha=0.1)
plt.xlabel('Years', fontsize=14)
plt.ylabel('e', fontsize=14)
ax.tick_params(axis='both', which='major', labelsize=14)

divider = make_axes_locatable(ax)

cba = divider.new_vertical(size='5%', pad=0.5)
cbb = divider.new_vertical(size='5%', pad=0.5)

fig.add_axes(cba)
fig.add_axes(cbb)

# add colorbar #1
cba = plt.colorbar(sc, cax=cba, orientation='horizontal')
ax.xaxis.set_ticks_position('default')
cba.ax.xaxis.set_ticks_position('top')
# add colorbar #2
cbb = plt.colorbar(sc1, cax=cbb, orientation='horizontal')
cbb.ax.invert_yaxis()
ax.xaxis.set_ticks_position('default')
cbb.ax.xaxis.set_ticks_position('top')
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM