![](/img/trans.png)
[英]How to add x and y labels for each individual plot subplots when x and y axis is shared?
[英]How to split y axis labels and color each part separately?
借用这篇优秀文章中的一些代码,可以通过偏移框将文本放在一起。
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.