python - Matplotlib 条形图:独立调整特定条形的 alpha 值
问题描述
我有一个简单的条形图,带有标签条。x 轴从过去日期移动到未来日期。我想在未来日期使用更大的 alpha 值来表明它们的值是估计值。我不知道如何调整 alpha。我找到了使用 'get_children()[].set_color() 更改颜色的建议,这是一个不错的解决方法,但我想改变 alpha 以获得更好的颜色匹配。我还尝试使用 alpha 值列表并在 for 循环中创建条形图。这有效,但我失去了标签。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig, ax = plt.subplots(figsize=(11,6))
req = [700, 600, 500, 450, 350, 300, 200, 150, 100, 50]
completed = [100, 100, 50, 100, 50, 100, 50, 50,50, 50]
Months=['May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec', 'Jan-21', 'Feb']
x = np.arange(len(req)) # the label locations
width = 0.4 # the width of the bars
#I got this to work using a for look on rects but then lost my 'autolabels'
#alphas_o=([.9, .9, .9, .9, .9, .9, .9, .5, .5, .5])
#alphas_c=([.9, .9, .9, .9, .9, .9, .5, .5, .5, .5])
rects1 = ax.bar(x - width/2, req, width, color='tab:orange', alpha = .9)
rects2 = ax.bar(x + width/2, completed, width, color='tab:blue', alpha =.9 )
#This is an OK work around, but changing alpha instead of color looks better
ax.get_children()[7].set_color('moccasin')
ax.get_children()[8].set_color('moccasin')
ax.get_children()[9].set_color('moccasin')
ax.get_children()[16].set_color('lightsteelblue')
ax.get_children()[17].set_color('lightsteelblue')
ax.get_children()[18].set_color('lightsteelblue')
ax.get_children()[19].set_color('lightsteelblue')
ax.set_ylabel('Counts',fontsize=12 )
ax.set_xticks(x)
ax.set_xticklabels(Months, fontsize=12)
#I put this legend in place when I used the for loop and list of alphas. It works fine
orange_patch = mpatches.Patch(color='tab:orange', label='Total Open Requests')
blue_patch = mpatches.Patch(color='tab:blue', label='Completed Requests')
ax.legend(handles=[orange_patch, blue_patch], frameon=False, fontsize=12, bbox_to_anchor=(.9, .8))
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
ax.tick_params(which='both',axis='y', left=False, right=False, labelleft=False, labelright=False)
# remove the frame of the chart
for spine in plt.gca().spines.values():
spine.set_visible(False)
plt.show()
解决方案
我使用的是 RGBA 格式的颜色格式,第四个值是 alpha 值,所以我使用您创建的 alpha 值列表来创建颜色列表。我已将其应用于条形图。
alphas_o=([.9, .9, .9, .9, .9, .9, .9, .5, .5, .5])
alphas_c=([.9, .9, .9, .9, .9, .9, .5, .5, .5, .5])
rgba_colors = np.zeros((10,4))
rgba_colors[:,0] = 1.0
rgba_colors[:, 3] = alphas_o
rgba_colors1 = np.zeros((10,4))
rgba_colors1[:,2] = 1.0
rgba_colors1[:, 3] = alphas_c
rects1 = ax.bar(x - width/2, req, width, color=rgba_colors)
rects2 = ax.bar(x + width/2, completed, width, color=rgba_colors1)
ax.set_ylabel('Counts',fontsize=12 )
ax.set_xticks(x)
ax.set_xticklabels(Months, fontsize=12)
orange_patch = mpatches.Patch(color='r', label='Total Open Requests')
blue_patch = mpatches.Patch(color='b', label='Completed Requests')
ax.legend(handles=[orange_patch, blue_patch], frameon=False, fontsize=12, bbox_to_anchor=(.9, .8))
推荐阅读
- python - 使用正则表达式获取带句点的电话号码
- scala - 转换字符串序列以连接列
- mysql - 如何消除工作台中的错误?
- python - 酌情将行从一个数据帧分配到另一个数据帧
- python - 球体上三角形的六边形:从二十面体网格构建六边形/测地线网格(仅限北极)
- vba - 如何将项目添加到包含分号的组合框(使用 AddItem())?
- javascript - 如何编写分组算法,通过具有 3 个或更多相似属性对数据集中的项目进行分组
- r - 计算字符串出现在组列中的次数
- mysql - 如何使用 ORDER BY 计算行数直到某个值
- angular - Angular - Laravel 获得记录最多的前 5 个 ID