【问题标题】:Altering the middle point of the colors assigned to a scatterplot using a colorbar in matplotlib使用 matplotlib 中的颜色条更改分配给散点图的颜色的中间点
【发布时间】:2022-12-12 06:14:58
【问题描述】:

我有一个简单的散点图,点上有一个颜色条,如下所示:

import pandas as pd
import matplotlib.pyplot as plt

col1, col2, col3 = [], [], []
for i in range(0,21):
    col1.append(i)
    col2.append(i**1.5)
    col3.append(i)
    
data = pd.DataFrame({'col1': col1, 'col2': col2, 'col3': col3})

fig = plt.figure()
ax = plt.axes()
im = ax.scatter(data['col1'], data['col2'], c=data['col3'], cmap='RdBu')
cbar = fig.colorbar(im, ax=ax)
plt.show()

我的c的数据范围是0到20,这里的colorbar会自动取10作为中间点,并相应地在散点图中对我的点进行着色,有没有办法自己分配colorbar的中间点?例如,在此示例中将中间点设置为 5 而不是 10,这样白色将被分配给 5,并且颜色条仍会从 0 到 20。

【问题讨论】:

    标签: python matplotlib scatter-plot colorbar


    【解决方案1】:

    您可以在绘图时传递 custom vmin, vmax, vcenter 参数。像这样。

    import pandas as pd
    import matplotlib.pyplot as plt
    import matplotlib.colors as mcolors
    
    
    col1, col2, col3 = [], [], []
    for i in range(0,21):
        col1.append(i)
        col2.append(i**1.5)
        col3.append(i)
        
    data = pd.DataFrame({'col1': col1, 'col2': col2, 'col3': col3})
    
    fig = plt.figure()
    ax = plt.axes()
    norm = mcolors.TwoSlopeNorm(vcenter=5)
      
    im = ax.scatter(data['col1'], data['col2'], c=data['col3'], cmap='RdBu', norm = norm )
    cbar = fig.colorbar(im, ax=ax)
    plt.show()
    

    给#

    【讨论】:

    • 抱歉,我没有明确指定,我严格来说是想设置一个中间数字,这样颜色条的末端就会适应,这样白色就会被分配给 5,而颜色条仍然会达到 20。
    • 编辑@BasR 这是你在找什么?如果不是,请发布你的输出应该是什么样子......我的想象力很差
    • 这正是我要找的是的,谢谢
    猜你喜欢
    • 1970-01-01
    • 2011-08-29
    • 2014-09-10
    • 1970-01-01
    • 2014-09-24
    • 2021-10-01
    • 2021-07-28
    • 2013-06-16
    • 2011-07-26
    相关资源
    最近更新 更多