python - 在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()
解决方案
用于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()
推荐阅读
- java - 如何在 android 上安装 url 编码器库?
- javascript - 从最后一行谷歌应用程序脚本再次增加 ID
- flutter - 如何在 Flutter 中获取文件的 base64
- java - Java 使用 jframe 在图像上绘制
- kubernetes - 从文件创建机密时,使用 Kubernetes 机密作为环境变量
- docker - 无法使用 RabbitMQ 集群 Kubernetes 算子创建 RabbitMQ 实例
- javascript - 导入数组的特定部分
- group-by - Splunk:按日志文件中的某些条目分组
- php - 为什么在 jquery 中循环对象数组后我得到未定义?
- r - 基于 R Shiny 中的 selectInput 的子集数据帧