如何将颜色条添加到plt.条形图?

2024-03-28 08:58:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个自更新图表,该图表根据感兴趣的y轴值显示水平线和颜色栏。因此,如果条形图肯定高于此值(给定95%的置信区间),则其颜色可能为红色;如果条形图肯定低于此值,则其颜色可能为蓝色;如果条形图包含此值,则其颜色可能为白色。类似于此:

plot with colorbar

我的问题是我不能在绘图上显示颜色栏。我根据LinearSegmentedColormap和一些条件为每个色条上色,但我无法在图像上显示此色条

这是我的代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from math import sqrt
import matplotlib.axes
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from matplotlib.cm import ScalarMappable
np.random.seed(12345)

df = pd.DataFrame([np.random.normal(32000,200000,3650), 
                   np.random.normal(43000,100000,3650), 
                   np.random.normal(43500,140000,3650), 
                   np.random.normal(48000,70000,3650)], 
                  index=[1992,1993,1994,1995])

means = []
for i in df.index:
    means.append(df.loc[i].mean())
    
std = []
for i in df.index:
    std.append(df.loc[i].std())

# compute the 95% confidence intervals
conf = []
for i in range(len(means)):
    margin = (1.96*std[i])/sqrt(len(df.columns))
    conf.append(margin)
fig, axs = plt.subplots(1)
bars = plt.bar(df.index, means, yerr= conf, tick_label = df.index, capsize = 10)

#Setup the plot
yinterest = 43000
plt.gca().spines.get('top').set_visible(False)
plt.gca().spines.get('right').set_visible(False)
plt.axhline(yinterest, color  = 'black', label = '4300')

#setting the y-interest tick
plt.draw()
labels = [w.get_text() for w in ax.get_yticklabels()]
locs=list(ax.get_yticks())
labels+=[str(yinterest)]
locs+=[float(yinterest)]
ax.set_yticklabels(labels)
ax.set_yticks(locs)
plt.draw()

#setting up the colormap
colormap = cm.get_cmap('RdBu', 10)
colores = []
for i in range(len(means)):
    color = (yinterest-(means[i]-conf[i]))/((means[i]+conf[i])-(means[i]-conf[i]))
    bars[i].set_color(colormap(color))

我对python(或编程)相当陌生,我到处都在寻找解决方案,但都没有结果。任何帮助都将不胜感激

你好


Tags: inimportdfforgetindexmatplotlib颜色
1条回答
网友
1楼 · 发布于 2024-03-28 08:58:19

第一个提示是使用pandasonic方法来计算绘图数据 (更加简洁):

means = df.mean(axis=1)
std = df.std(axis=1)
conf = (std * 1.96 / sqrt(df.shape[1]))

要绘制绘图,请运行:

yinterest = 39541
fig, ax = plt.subplots(figsize=(10,6))
ax.spines.get('top').set_visible(False)
ax.spines.get('right').set_visible(False)
colors = (yinterest - (means - conf)) / (2 * conf)
colormap = plt.cm.get_cmap('RdBu', 10)
plt.bar(df.index, means, yerr=conf, tick_label=df.index, capsize=10, color=colormap(colors))
cbar = plt.colorbar(plt.cm.ScalarMappable(cmap=colormap), orientation='horizontal')
cbar.set_label('Color', labelpad=5)
plt.axhline(yinterest, color='black', linestyle=' ', linewidth=1)
plt.show()

有一个技巧可以避免在使用后给条上色 生成是我计算颜色,然后将其转换为 一个颜色映射并传递到plt.bar

要绘制颜色栏,请使用plt.colorbar

我将yinterest的值更改为包含在图片中的值,并获得了 类似于您的图片,但带有颜色栏:

enter image description here

相关问题 更多 >