根据第三个变量更改某些部分中颜色条的颜色

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

我有以下代码。我试图让 De_below_line 的值在颜色条上显示为不同的颜色。颜色条本身的范围应从 De.min() 到 De.max()。虽然我可以让颜色在散点图上以不同的方式绘制,但这些值并不容易转移到颜色栏。我在下面添加了一张可能的颜色条的图片,展示了我希望它的外观,并希望澄清我想要做什么。任何帮助将不胜感激。

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FormatStrFormatter
    from matplotlib.colors import ListedColormap
    
    xls = pd.ExcelFile('20240109 - CPeT Export - Rev2.xlsx')
    God = pd.ExcelFile('20231213-Vs calculations.xlsx')
    n = len(xls.sheet_names)
    #------Raw data-------------------------------------------------------------------------------------#
    dfs = pd.read_excel(xls, sheet_name='SCPTU-12-CPT', skiprows=185, skipfooter=0)
    title = dfs.values[0,0]
    qt = dfs.values[:,5]                                        # Cone tip resistance (MPa)
    ov = dfs.values[:,10]                                       # Vertical total stress (kPa)
    Qtn = dfs.values[:,18]                                      # Normalised cone tip resistance with stress component (-)
    De = dfs.values[:,1]                                        # Imports depth values (m)
    Gor = pd.read_excel(God, sheet_name='SCPTU-12-CPT', skiprows=185, skipfooter=0)
    Go = Gor.values[:,8]                                        # Imports the correct small-strain shear modulus (MPa)
    D = Gor.values[:,0]                                         # Imports depth values (m)
    #------Calculations---------------------------------------------------------------------------------#
    ov = ov/1000
    qn = qt-ov                                                  # Calculates qn
    IG = Go/qn                                                  # Calculates normalised rigidty index
    #------Plotting the results-------------------------------------------------------------------------#
    fig = plt.figure()
    
    y = 2280.4*IG**-1.333
    De_below_line = De[Qtn < y]
    
    cmap = ListedColormap(['blue', 'red'])  # Two colors: below the line, above the line
    colors = np.where(Qtn < y, 'blue', 'red')  # De.min() for below the line, De.max() for above the line
    
    ax = fig.gca()
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))
    ax.xaxis.set_major_formatter(FormatStrFormatter('%g'))
    plt.xlabel('Normalised Rigidity Index, $I_G$')
    plt.ylabel('Normalised Cone Tip Resistance, Qtn')
    sc = ax.scatter(IG, Qtn, s=60, label=title, c=colors, cmap=cmap)
    plt.plot([1,330],[(330/1)**(1/0.75),1], linewidth=1, color="black",linestyle='-', marker='None')
    
    cbar = plt.colorbar(sc, ticks=[De.min(), De.max()])
    cbar.ax.invert_yaxis()
    
    ax.set_xlim(1, 1000)
    ax.set_ylim(1, 1000)
    plt.show()

python matplotlib colorbar
1个回答
0
投票

看起来您不想要常规的颜色条。使用

imshow
,您可以显示
DE
值的自定义属性。表达式
Qtn < y
(其中两个部分都是 numpy 数组)将转换为具有
False
True
值的新数组。当解释为数字时,它变成
0
1
。更改颜色图中颜色的顺序会将
1
True
,因此
Qtn < y
映射为蓝色)和
0
映射为红色。

imshow
需要其输入为 2D,因此需要重新调整数组的形状。
aspect='auto'
避免了默认的“方形像素”。
origin='lower'
让图像从底部开始。
extent
xmin, xmax, ymin, ymax
设置为坐标(x 值并不重要)。

下面的代码创建了一个带有两个子图的图形:左侧的散点图和右侧的条形图。该代码假设

DE
数组严格从低到高排序。

import matplotlib.pyplot as plt
from matplotlib. Colors import ListedColormap
import numpy as np

cmap = ListedColormap(['crimson', 'skyblue'])  # Two colors: above the line, below the line

# create some random data for testing
np.random.seed(1123)
IG = np.logspace(0, 3, 20)
Qtn = np.random.uniform(2, 999, 20)
y = 2280.4 * IG ** -1.333
De = np.linspace(0, 100, 20)

fig, (ax, ax_DE) = plt.subplots(ncols=2, figsize=(8, 6), gridspec_kw={'width_ratios': [10, 1]})

# create the scatter plot IG vs Qtn
ax.set_xscale('log')
ax.set_yscale('log')
ax.scatter(IG, Qtn, s=60, label='IG vs Qtn', c=(Qtn < y), cmap=cmap)
# ax. Plot([1, 330], [(330 / 1) ** (1 / 0.75), 1], linewidth=1, color="black", linestyle='-', marker='None')
ax.plot(IG, y, linestyle='-', color='black', label='y')
ax.set_xlabel('IG')
ax.set_ylabel('Qtn')
ax.set_title('IG vs Qtn')

# create the bar for DE
ax_DE.imshow((Qtn < y).reshape(-1, 1), aspect='auto', cmap=cmap, origin='lower', extent=(0, 1, De.min(), De.max()))
ax_DE.set_xticks([])  # erase x ticks
ax_DE.yaxis.tick_right()  # place y ticks at the right
ax_DE.set_title('Depth')

plt.tight_layout()
plt.show()

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