简体   繁体   English

如何在matplotlib中的绘图画布内放置可变长度的刻度标签?

[英]How to put variable length tick labels inside the plot canvas in matplotlib?

I want to turn this: 我想转这个: 现在看起来像什么 into something resembling this: 变成类似这样的东西: 它应该是什么样子

All of the instructions I have come across just apply an offset to the label position and therefore only work if the labels are of a known width. 我遇到的所有说明都仅对标签位置加上偏移量,因此仅在标签的宽度已知时才起作用。

code to produce a similar plot than the example: 代码生成与示例相似的绘图:

#!/usr/bin/env python3
import matplotlib.pyplot as plt
yvalues = [ 'short name', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'slightly longer name' ]
xvalues = [ [1, 5], [3, 7], [2, 6] ]
fig, ax = plt.subplots()
fig.set_size_inches(1280/fig.get_dpi(), 720/fig.get_dpi())
ax.axvline(40)
for i in range(len(yvalues)):
    ax.plot(xvalues[i], (yvalues[i], yvalues[i]))
plt.show()

Adding the following two lines to your code 在代码中添加以下两行

ax.tick_params(axis="y", direction="in", pad=-10)
plt.setp(ax.get_yticklabels(),ha="left")

will result in the following plot 将导致以下情节

在此处输入图片说明

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

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