首页 > 解决方案 > 在python中为条形图添加标签

问题描述

像这样

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot()

N = 5
ind = np.arange(N)
width = 0.5
vals = []

colors = []
add_c=[(1,0),(4,1),(-1,0),(3,0),(2,1)]
for v in add_c:
    vals.append(v[0])
    if v[0] == -1:
        colors.append('r')
    else:
        if v[1] == 0:
            colors.append('b')
        else:
            colors.append('g')

ax.bar(ind, vals, width, color=colors,label=[{'r':'red'}])
ax.legend()
ax.axhline(y = 0, color = 'black', linestyle = '-')
plt.show()

大家好,我正在标记我的条形图,它具有“绿色”、“红色”和“蓝色”三种颜色,我只想在图表的右上角显示名称和颜色。三色代码图

标签: pythonpython-3.xmatplotliblabelaxis-labels

解决方案


用于mpatches手动构建您的图例:

import matplotlib.patches as mpatches:

...

color_dict = {'cat1': 'r', 'cat2': 'g', 'cat3': 'b'}
labels = color_dict.keys()
handles = [mpatches.Rectangle((0,0),1,1, color=color_dict[l]) for l in labels]

ax.bar(ind, vals, width, color=colors)
ax.legend(handles, labels)

完整代码:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

fig = plt.figure()
ax = fig.add_subplot()

N = 5
ind = np.arange(N)
width = 0.5
vals = []

colors = []
add_c=[(1,0),(4,1),(-1,0),(3,0),(2,1)]
for v in add_c:
    vals.append(v[0])
    if v[0] == -1:
        colors.append('r')
    else:
        if v[1] == 0:
            colors.append('b')
        else:
            colors.append('g')

color_dict = {'cat1': 'r', 'cat2': 'g', 'cat3': 'b'}
labels = color_dict.keys()
handles = [mpatches.Rectangle((0,0),1,1, color=color_dict[l]) for l in labels]

ax.bar(ind, vals, width, color=colors)
ax.legend(handles, labels)
ax.axhline(y = 0, color = 'black', linestyle = '-')
plt.show()

在此处输入图像描述


推荐阅读