Matplotlib Table- Assign different text alignments to different columns

2024/10/1 3:34:10

I am creating a two column table and want the text to be as close as possible. How can I specify that the first column be right aligned and the second be left aligned?

I've tried by setting the general cellloc to one side (cellloc sets the text alignment)

from matplotlib import pyplot as pltdata = [['x','x'] for x in range(10)]
bbox = [0,0,1,1]tb = plt.table(cellText = data, cellLoc='right', bbox = bbox)
plt.axis('off') # get rid of chart axis to only show table

Then looping through cells in the second columns to set them to left align:

for key, cell in tb.get_celld().items():if key[1] == 1: # if the y value is equal to 1, meaning the second columncell._text.set_horizontalalignment('left') # then change the alignment

This loop immediately above has no effect, and the text remains right aligned.

Am I missing something? Or is this not possible?

EDIT

A workaround is for me to separate the data into two different lists, one for each column. This produces the results I'm looking for, but I'd like to know if anyone knows of another way.

data_col1 = [xy[0] for xy in data]
data_col2 = [xy[1] for xy in data] tb = plt.table(cellText = data_col2, rowLabels=data_col1, cellLoc='left', rowLoc='right', bbox = bbox)
Answer

Instead of setting the alignment of the text itself, you need to set the position of the text inside the table cell. This is determined by the cell's ._loc attribute.

def set_align_for_column(table, col, align="left"):cells = [key for key in table._cells if key[1] == col]for cell in cells:table._cells[cell]._loc = aligntable._cells[cell]._text.set_horizontalalignment('left') 

Some complete example:

from matplotlib import pyplot as pltdata = [['x','x'] for x in range(10)]
bbox = [0,0,1,1]tb = plt.table(cellText = data, cellLoc='right', bbox = bbox)
plt.axis('off') # get rid of chart axis to only show tabledef set_align_for_column(table, col, align="left"):cells = [key for key in table._cells if key[1] == col]for cell in cells:table._cells[cell]._loc = aligntable._cells[cell]._text.set_horizontalalignment('left') set_align_for_column(tb, col=0, align="right")
set_align_for_column(tb, col=1, align="left")plt.show()

enter image description here

(The approach used here is similar to changing the cell padding as in this question: Matplotlib Text Alignment in Table)

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

Related Q&A

How would I make a random hexdigit code generator using .join and for loops?

I am new to programming and one assignment I have to do is create a random hexdigit colour code generator using for loops and .join. Is my program below even close to how you do it, or is it completely…

Multiline python regex

I have a file structured like this : A: some text B: more text even more text on several lines A: and we start again B: more text more multiline textIm trying to find the regex that will split my file …

How can I process xml asynchronously in python?

I have a large XML data file (>160M) to process, and it seems like SAX/expat/pulldom parsing is the way to go. Id like to have a thread that sifts through the nodes and pushes nodes to be processed …

python postgresql: reliably check for updates in a specific table

Situation: I have a live trading script which computes all sorts of stuff every x minutes in my main thread (Python). the order sending is performed through such thread. the reception and execution of …

How to push to remote repo with GitPython

I have to clone a set of projects from one repository and push it then to a remote repository automatically. Therefore im using python and the specific module GitPython. Until now i can clone the proje…

How do I do use non-integer string labels with SVM from scikit-learn? Python

Scikit-learn has fairly user-friendly python modules for machine learning.I am trying to train an SVM tagger for Natural Language Processing (NLP) where my labels and input data are words and annotatio…

Python - walk through a huge set of files but in a more efficient manner

I have huge set of files that I want to traverse through using python. I am using os.walk(source) for the same and is working but since I have a huge set of files it is taking too much and memory resou…

Python: handling a large set of data. Scipy or Rpy? And how?

In my python environment, the Rpy and Scipy packages are already installed. The problem I want to tackle is such:1) A huge set of financial data are stored in a text file. Loading into Excel is not pos…

Jupyter notebook - cant import python functions from other folders

I have a Jupyter notebook, I want to use local python functions from other folders in my computer. When I do import to these functions I get this error: "ModuleNotFoundError: No module named xxxxx…

Can pandas plot a time-series without trying to convert the index to Periods?

When plotting a time-series, I observe an unusual behavior, which eventually results in not being able to format the xticks of the plot. It seems that pandas internally tries to convert the index into …