0

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']))```
firefly
  • 339
  • 2
  • 10
  • 1
    Does this answer your question? [Scale matplotlib.pyplot.Axes.scatter markersize by x-scale](https://stackoverflow.com/questions/48172928/scale-matplotlib-pyplot-axes-scatter-markersize-by-x-scale) – Mr. T Jan 20 '21 at 10:32
  • 1
    See also this interesting thread: https://stackoverflow.com/q/14827650/8881141 – Mr. T Jan 20 '21 at 10:33
  • Yes! Both very helpful indeed, thank you. – firefly Jan 20 '21 at 19:18

1 Answers1

1

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

Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28