mossymountain
mossymountain

Reputation: 183

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

I want to turn this:what it looks like now into something resembling this:what it should look like

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()

Upvotes: 1

Views: 1019

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339570

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

enter image description here

Upvotes: 1

Related Questions