简体   繁体   English

如何拆分 y 轴标签并分别为每个部分着色?

[英]How to split y axis labels and color each part separately?

ax.yaxis.get_major_ticks() allows me to colour-code each label differently. ax.yaxis.get_major_ticks()允许我对每个 label 进行不同的颜色编码。 But I'm failing to split the label and mark each part with a different colour.但我未能拆分 label 并用不同的颜色标记每个部分。

Example Image: A_B => A in Blue and _B in Red, similarly C_D => C in Blue and D in Red etc.示例图像: A_B => 蓝色的 A和红色的_B ,类似地C_D => 蓝色的C和红色的D等。

While looping through all the ticks the text is available with get_text() , but color coding each part separately is not possible with the same.在遍历所有刻度时,文本可通过get_text()获得,但无法单独对每个部分进行颜色编码。

This a sample graphical representation of a horizontally stacked bar chart:这是水平堆叠条形图的示例图形表示:

图片

Borrowing some code from this excellent post , text can be put together via offset boxes.借用这篇优秀文章中的一些代码,可以通过偏移框将文本放在一起。

import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker

fig, ax = plt.subplots()

vals1 = [0.3, 0.5, 0.4, 0.2, 0.5]
vals2 = [0.2, 0.3, 0.2, 0.2, 0.1]
labels1 = ['A', 'B', 'CCCC', 'DDDDDD', 'E']
labels2 = ['B', 'CCCC', 'DDDDDD', 'E', 'F']
color1 = 'dodgerblue'
color2 = 'crimson'

ax.barh(range(len(vals1)), vals1, color=color1)
ax.barh(range(len(vals2)), vals2, left=vals1, color=color2)

ax.set_yticklabels([])
for i in range(len(labels1)):
    boxes = [TextArea(text, textprops=dict(color=color))
             for text, color in zip([labels1[i], '_', labels2[i]], [color1, 'black', color2])]
    xbox = HPacker(children=boxes, align="right", pad=1, sep=1)
    anchored_xbox = AnchoredOffsetbox(loc='center right', child=xbox, pad=0, frameon=False, bbox_to_anchor=(0, i),
                                      bbox_transform=ax.transData, borderpad=1)
    ax.add_artist(anchored_xbox)

plt.tight_layout()
plt.show()

结果图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM