Home > OS >  Python: How to add text on plot 2D mesh "TypeError: 'str' object is not a mapping&quo
Python: How to add text on plot 2D mesh "TypeError: 'str' object is not a mapping&quo

Time:12-12

I am looking for adding node number on the plot as the figure attached. unfortunately, I started with the following code, however it generates the following erenter image description hereror "TypeError: 'str' object is not a mapping", given the following information, coordinates of each node, what nodes belong to each element, and the value each node has.

import numpy as np
from matplotlib import pyplot as plt
el_con=np.array([[0,3,4,1],[1,4,5,2]])
coord=np.array([[0,0,0],[0,0,.0625],[0,0,.1250],[25,0,0],[25,0,0.0625],[25,0,.1250]])

for i in range (len(el_con)):
       el_con_n=el_con[i,:]
       X = coord[el_con[i,:],0].reshape((-1, 1))
       Y = coord[el_con[i,:],1].reshape((-1, 1))
       Z = coord[el_con[i,:],2].reshape((-1, 1))
       plt.fill(X, Z, edgecolor='black', fill=False)
       for j in range (2):
           x=el_con[i][j]
           plt.text(X[j],Y[j],Z[j],str(x))
plt.show()

CodePudding user response:

You seem to be (attempting to) add text using the Z index/coordinate when the plt.text() method only takes two coordinates (x and y) as parameters. The specification for plt.text() is as follows:

matplotlib.pyplot.text(x: float, y: float, s: str, fontdict=None, **kwargs)

where x and y are the X and Y coordinates and s is the Str containing the text you wish to add to the image.

In other words, remove the 3rd parameter which should be a string and not a coordinate.

plt.text(X[j], Y[j], str(x))

Your complete code should look like this, now:

import numpy as np
from matplotlib import pyplot as plt
el_con = np.array([[0, 3, 4, 1], [1, 4, 5, 2]])
coord = np.array([
    [0, 0, 0],
    [0, 0, .0625],
    [0, 0, .1250],
    [25, 0, 0],
    [25, 0, .0625],
    [25, 0, .1250],
    ])

for i in range(len(el_con)):
    el_con_n = el_con[i]  # Note: second index is redundant. Use `el_con[i]` instead.
    X = coord[el_con_n, 0].reshape((-1, 1))
    Y = coord[el_con_n, 1].reshape((-1, 1))
    Z = coord[el_con_n, 2].reshape((-1, 1))
    plt.fill(X, Z, edgecolor='black', fill=False)
    for j in range(2):
        x = el_con[i][j]
        plt.text(X[j], Y[j], str(x))
plt.show()

Note that you might have to replace the Y[j] with Z[j] while still only keeping two coordinates on the plt.text(x, y, s) line, because it looks like Z may actually be your y coordinate.

  • Related