Matplotlib text alignment

2024/5/19 15:56:41

Is there a way to get the result shown in the third axes with just a single ax.text() command? Using expandtabs almost get me there, but the text never aligns properly.

Using two plotting commands doesn't seem like a good practice to me, and you always need to guess the distance between both, which might take some iterations.

fig, axs = plt.subplots(1,3, figsize=(12,4), subplot_kw={'aspect': 1, 'xticks': [], 'yticks':[]})
fig.subplots_adjust(wspace=0.05)values = {'a': 1.35, 'b': 25.1, 'c': 5}tmpl = """Param1: {a:1.1f}
Long param2: {b:1.1f}
Prm3: {c:1.1f}"""mystr = tmpl.format(**values)
axs[0].text(0.1, 0.9, mystr, va='top', transform=axs[0].transAxes)
axs[0].set_title('Default')tmpl = """Param1:\t\t\t{a:1.1f}
Long param2:\t{b:1.1f}
Prm3:\t\t\t{c:1.1f}""".expandtabs()mystr = tmpl.format(**values)
axs[1].text(0.1, 0.9, mystr, va='top', transform=axs[1].transAxes)
axs[1].set_title('Almost there')labels = """Param1:
Long param2:
Prm3:"""tmpl = """{a:1.1f}
{b:1.1f}
{c:1.1f}"""mystr = tmpl.format(**values)
axs[2].text(0.1, 0.9, labels, va='top', transform=axs[2].transAxes)
axs[2].text(0.65, 0.9, mystr, va='top', ha='right', transform=axs[2].transAxes)
axs[2].set_title('Target')

enter image description here

Answer

Use a monospaced font so that each character takes the same amount of space.

import matplotlib.pyplot as pltfig, axs = plt.subplots(1,3, figsize=(12,4), subplot_kw={'aspect': 1, 'xticks': [], 'yticks':[]})
fig.subplots_adjust(wspace=0.05)values = {'a': 1.35, 'b': 25.1, 'c': 5}tmpl = """Param1: {a:1.1f}
Long param2: {b:1.1f}
Prm3: {c:1.1f}"""mystr = tmpl.format(**values)
axs[0].text(0.1, 0.9, mystr, va='top', transform=axs[0].transAxes)
axs[0].set_title('Default')mono = {'family' : 'monospace'}textblock = "1234567890\nabcdefghij\nABCDEFGHIJ\n         0"axs[1].text(0.1, 0.9, textblock, va='top', transform=axs[1].transAxes, fontdict=mono)
axs[1].set_title('Monospaced text block')axs[2].text(0.1, 0.9, textblock, va='top', transform=axs[2].transAxes)
axs[2].set_title('Not monospaced')plt.show()

enter image description here

https://en.xdnf.cn/q/72879.html

Related Q&A

Pandas cannot load data, csv encoding mystery

I am trying to load a dataset into pandas and cannot get seem to get past step 1. I am new so please forgive if this is obvious, I have searched previous topics and not found an answer. The data is mos…

How to read in an edge list to make a scipy sparse matrix

I have a large file where each line has a pair of 8 character strings. Something like:ab1234gh iu9240ghon each line.This file really represents a graph and each string is a node id. I would like to r…

How can I find the best fuzzy string match?

Pythons new regex module supports fuzzy string matching. Sing praises aloud (now). Per the docs:The ENHANCEMATCH flag makes fuzzy matching attempt to improve the fitof the next match that it finds.The …

how to write a unicode csv in Python 2.7

I want to write data to files where a row from a CSV should look like this list (directly from the Python console):row = [\xef\xbb\xbft_11651497, http://kozbeszerzes.ceu.hu/entity/t/11651497.xml, "…

Terminating QThread gracefully on QDialog reject()

I have a QDialog which creates a QThread to do some work while keeping the UI responsive, based on the structure given here: How To Really, Truly Use QThreads; The Full Explanation. However, if reject(…

Python descriptors with old-style classes

I tried to google something about it. Why do non-data descriptors work with old-style classes?Docs say that they should not: "Note that descriptors are only invoked for new style objects or class…

Decrypting a file to a stream and reading the stream into pandas (hdf or stata)

Overview of what Im trying to do. I have encrypted versions of files that I need to read into pandas. For a couple of reasons it is much better to decrypt into a stream rather than a file, so thats m…

How to replace accents in a column of a pandas dataframe

I have a dataframe dataSwiss which contains the information Swiss municipalities. I want to replace the letter with accents with normal letter.This is what I am doing:dataSwiss[Municipality] = dataSwis…

Comparison of multi-threading models in Julia =1.3 and Python 3.x

I would like to understand, from the user point of view, the differences in multithreading programming models between Julia >= 1.3 and Python 3.Is there one that is more efficient than the other (in…

How to do multihop ssh with fabric

I have a nat and it has various server So from my local server I want to go to nat and then from nat i have to ssh to other machinesLocalNAT(abcuser@publicIP with key 1)server1(xyzuser@localIP with key…