firefly
firefly

Reputation: 361

Changing x, y axis changes Matplotlib scatter bubbles

I am trying to make a labelled bubble plot. I have specified the location of each bubble at x,y in a df. My issue is that the plot cuts off the edges of the bubbles:

enter image description here

I thought I could correct this by changing the x and y axis limits, however this also moves the bubbles:

enter image description here

I have looked for solutions and tried adding ax.margins(2, 2) but this also does not work:

enter image description here

I'm really interested to know why this happens? And how to fix it please? Many thanks in advance. Here is my code, including what I've tried:

x = [-0.3, 1.5, 2.3, 2, 4.3, 0, 2.9]
y = [0.94, 1.04, 1.5, 0.7, 1.3, 1.55, 1]
size = [5850, 2600, 6500, 1300, 4550, 7150, 1950]
label = ['a', 'b', 'c', 'd', 'e', 'f', 'g']

df = pd.DataFrame({
'x': x,
'y': y,
's': size,
'label': label
})

fig, ax = plt.subplots(facecolor='w')

#plt.xlim(-2,7)
#plt.ylim(0.4,2)

#ax.margins(2, 2) 

for key, row in df.iterrows():
    ax.scatter(row['x'], row['y'], s=row['s']*5, alpha=.5)
    ax.annotate(row['label'], xy=(row['x'], row['y']))```

Upvotes: 0

Views: 189

Answers (1)

Roman Pavelka
Roman Pavelka

Reputation: 4191

Your problem is that marker size s is in image points**2, not in coordinated units:

https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.scatter.html

You can verify it, open the console and write:

import matplotlib.pyplot as plt
plt.ion()
plt.scatter([0], [0], s=10)
# Check, how it looks now
plt.xlim(-5, 5)
# Check that it looks the same

scatter is not right tool for this job. Use Ellipse, here there is some inspiration:

https://matplotlib.org/3.3.3/gallery/shapes_and_collections/ellipse_demo.html#sphx-glr-gallery-shapes-and-collections-ellipse-demo-py

Upvotes: 1

Related Questions