matplotlib 如何根据色彩图为条形图着色?

gfttwv5a  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(76)

我想根据侧面的颜色图更改条形图中条形的颜色。对于四个条形图中的每一个,它都应该取值x(在0和1之间浮动),在色图上找到这个值并相应地为条形图着色。我该怎么处理呢?我发现一些线程,问类似的问题,但我不能让它工作。我在Jupyter Notebook工作

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.cm import ScalarMappable
import ipywidgets as widgets
from ipywidgets import interact
import scipy.stats as st

def graph(#widgets#):
    ## Formats color bar.  Need the scalar mapable to enable use of the color bar.
    my_cmap = plt.cm.get_cmap('Reds')
    sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(vmin=0, vmax=1))
    cbar = plt.colorbar(sm)
    cbar.set_label('Probability')
    
    ## Test each bar against the range and determine probability of inclusion in range.
    for bar in s:
        ## find confidence interval max, min, and siee
        barmin = s - error_min
        barmax = s + error_max
        barsize = barmax - barmin
        ## Use the barmax/min and the selected range max/min to find the percentage of overlap.
        overlap = np.maximum(0, np.minimum(barmax, toprange) - np.maximum(barmin, bottomrange))
        length = barmax-barmin + toprange-bottomrange
        lengthx = barmax-barmin
        lengthy = toprange-bottomrange
 
        return 2*overlap/length, overlap/lengthx, overlap/lengthy
        
        average, x,y = overlap_percentage(x,y)

plt.show()

字符串
我试着用旁边的颜色图给条形图上色:


的数据

yizd12fk

yizd12fk1#

因为您说过每个条形图都有从0到1的值,所以您只需要将这些值作为条形图函数中的color参数传递给色彩Map表。

import matplotlib.pyplot as plt
import numpy as np

N = 10
x = np.arange(0, N)
y = np.random.uniform(low=20, high=100, size=N)
vals = np.random.random(N)

my_cmap = plt.get_cmap('Reds')
sm = plt.cm.ScalarMappable(cmap=my_cmap, norm=plt.Normalize(vmin=0, vmax=1))

fig, ax = plt.subplots()
p = ax.bar(x, y, color=my_cmap(vals))
fig.colorbar(sm, ax=ax)
fig.show()

字符串


的数据

相关问题