JakobJakobson13
JakobJakobson13

Reputation: 145

Matplotlib: plt.text with user-defined circle radii

Dear stackoverflow users,

I want to plot some data labels with its coordinates in a x,y-plot. Around the labels I want to put a circle with a user-defined radius as I want to symbolize the magnitude of the data property by the radius of the circle.

An example dataset could look like the following:

point1 = ["label1", 0.5, 0.25, 1e0] # equals [label, x, y, radius]
point2 = ["label2", 0.5, 0.75, 1e1] # equals [label, x, y, radius]

I want to use a code silimar to the following one:

import matplotlib.pyplot as plt

plt.text(point1[1], point1[2], point1[0], bbox = dict(boxstyle="circle")) # here I want to alter the radius by passing point1[3]
plt.text(point2[1], point2[2], point2[0], bbox = dict(boxstyle="circle")) # here I want to alter the radius by passing point2[3]
plt.show()

Is this possible somehow or is the plt.add_patch variant the only possible way?

Regards

Upvotes: 1

Views: 2190

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339430

In principle, you can use the boxes' pad parameter to define the circle size. However this is then relative to the label. I.e. a small label would have a smaller circle around it for the same value of pad than a larger label. Also the units of pad are fontsize (i.e. if you have a fontsize of 10pt, a padding of 1 would correspond to 10pt).

import numpy as np
import matplotlib.pyplot as plt

points = [["A", 0.2, 0.25, 0],          # zero radius
          ["long label", 0.4, 0.25, 0],  # zero radius
          ["label1", 0.6, 0.25, 1]] # one radius


for point in points:
    plt.text(point[1], point[2], point[0], ha="center", va="center",
             bbox = dict(boxstyle=f"circle,pad={point[3]}", fc="lightgrey")) 

plt.show()

Also

I don't know in how far this is desired.

I guess usually you would rather create a scatterplot at the same positions as the text

import numpy as np
import matplotlib.pyplot as plt

points = [["A", 0.2, 0.25, 100],          # 5 pt radius
          ["long label", 0.4, 0.25, 100], # 5 pt radius
          ["label1", 0.6, 0.25, 1600]]   # 20 pt radius

data = np.array([l[1:] for l in points])
plt.scatter(data[:,0], data[:,1], s=data[:,2], facecolor="gold")

for point in points:
    plt.text(point[1], point[2], point[0], ha="center", va="center") 

plt.show()

enter image description here

Upvotes: 2

Related Questions