0

I have a csv file that shows some references and their coordinates for some electronic parts:

The output of the csv file using df = pandas.read_csv(.......)

I've been working about drawing rectangles for these references using matplotlib.pyplot, matplotlib.patches and Rectangle:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from patches import Rectangle

fig = plt.figure()
ax = fig.add_subplot(111)

I decided to create rectangles for these coordinates and set their "Part ID" from the csv file as their names using plt.text:

n=0

for n in range(30):
    z = df['Part ID'][n]
    rect_n = patches.Rectangle((df['X'][n], df['Y'][n]), 200, 300, fill = False)

(I randomly chose 200 as width and 300 as height. Don't mind that.)

for n in range(30):
    z_n = df['Part ID'][n]
    rect_n = patches.Rectangle((df['X'][n], df['Y'][n]), 200, 300, fill = False)
    ax.add_patch(rect_n)
    plt.text((df['X'][n], df['Y'][n]), 'ID: %s' % (z_n))

df.plot(kind='scatter', x='X', y='Y', ax=ax)
ax.set_axisbelow(True)
ax.grid(linestyle='-', linewidth='2', color='g')

In plt.text row, i tried to name the Rectangles with their Part ID from the csv file. I created a variable z and set the names to z as string. The exact problem starts here:

When i started to run the program, all of the code works fine without naming them as their Part ID.

Full Plot Drawing of the csv file without naming them

After this drawing, i decided to add the plt.text row for naming them.

But i get the error: TypeError: text() missing 1 required positional argument: 's'

There is a problem about string assigning in plt.text(.....%s). Is there anyone that knows what to do?

How can i assign each of them their Part ID names?

tmdavison
  • 64,360
  • 12
  • 187
  • 165

1 Answers1

0

The call signature for plt.text is:

plt.text(x, y, s, ...)

Note that x, y, and s are all arguments to this function.

You have used:

plt.text((df['X'][n], df['Y'][n]), 'ID: %s' % (z_n))

where you have given the x, y coordinates as the tuple (df['X'][n], df['Y'][n]). Remove the parentheses from around them, and it should work just fine:

plt.text(df['X'][n], df['Y'][n], 'ID: %s' % (z_n))

Better yet, to make sure you are giving the correct arguments to the function, you could name the arguments:

plt.text(x=df['X'][n], y=df['Y'][n], s='ID: %s' % (z_n))
tmdavison
  • 64,360
  • 12
  • 187
  • 165
  • Thank you very much! I didn't think about assigning x,y,s seperately. I thought comma would be enough for seperating but i was wrong. Thanks again, have a nice day! – Ziya_Anil_SEN_98 Aug 20 '20 at 11:09