python – Matplotlib:将y-ticks左对齐
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – Matplotlib:将y-ticks左对齐,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2020字,纯文字阅读大概需要3分钟。
内容图文
我有可变长度的刻度标签,我想将它们对齐到左边(即在较短的轴和y轴之间有一个空格).有没有合理的方法来做到这一点?
使用水平对齐“左”将它们对齐到左侧,但它们都从轴开始,因此它们最终在图中.所以另一个问题可能是 – 我可以改变他们的出发点吗?
示范代码:
import numpy as np
import matplotlib.pyplot as plt
ticks = ["Lorem ipsum dolor sit amet, consectetur adipisicin", "g elit, sed do", "eiusmod tempor incididunt ut labo", "re et dolore magna ali", "qua. Ut en", "im ad minim veniam, quis nostr", "ud exercitation ullamco labo", "ris nisi ut aliquip ex ea c", "ommodo co", "nsequat. Duis aute irure dolor in rep"]
data = [5,1,2,4,1,4,5,2,1,5]
ind = np.arange(len(data))
fig = plt.figure()
ax = plt.subplot(111)
ax.barh(ind, data, 0.999)
ax.set_yticks(ind + 0.5)
r = ax.set_yticklabels(ticks)#, ha = 'left')
fig.set_size_inches(12, 8)
fig.savefig(r'C:\try.png', bbox_extra_artists=r, bbox_inches='tight')
解决方法:
你只需要添加一个垫.见matplotlib ticks position relative to axis
yax = ax.get_yaxis()
yax.set_tick_params(pad=pad)
要弄清楚垫应该是什么:
import numpy as np
import matplotlib.pyplot as plt
ticks = ["Lorem ipsum dolor sit amet, consectetur adipisicin", "g elit, sed do", ? ? ?"eiusmod tempor incididunt ut labo", "re et dolore magna ali", "qua. Ut en", "im ad minim veniam, quis nostr", "ud exercitation ullamco labo", "ris nisi ut aliquip ex ea c", "ommodo co", "nsequat. Duis aute irure dolor in rep"]
data = [5,1,2,4,1,4,5,2,1,5]
ind = np.arange(len(data))
fig = plt.figure(tight_layout=True) # need tight_layout to make everything fit
ax = plt.subplot(111)
ax.barh(ind, data, 0.999)
ax.set_yticks(ind + 0.5)
r = ax.set_yticklabels(ticks, ha = 'left')
fig.set_size_inches(12, 8, forward=True)
# re-size first, the shift needs to be in display units
plt.draw() # this is needed because get_window_extent needs a renderer to work
yax = ax.get_yaxis()
# find the maximum width of the label on the major ticks
pad = max(T.label.get_window_extent().width for T in yax.majorTicks)
yax.set_tick_params(pad=pad)
plt.draw()
内容总结
以上是互联网集市为您收集整理的python – Matplotlib:将y-ticks左对齐全部内容,希望文章能够帮你解决python – Matplotlib:将y-ticks左对齐所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。