1

I have the below code and am trying to add a legend. Unfortunately every time I do this it adds a huge coloured dot next to it.

I have tried

ax.legend(["Name"])

It still gives a big dot

My current attempt is:

fig, axi = plt.subplots(figsize=(13,10))
colors = ["blue","green","pink","yellow","cyan","orange","red"]
sizes = 100*df["Indexed Pages (00s)"]
brand = df["Brand"]
x = df["Optimisation Score"].to_numpy()
y = df["Market Share %"].to_numpy()
for i in range(len(x)):
    axi.scatter(x[i],y[i], color=colors[i],s=sizes[i], alpha=0.4, label=brand[i])

axi.set_xlabel("Optimisation Score", fontsize="20")
axi.set_ylabel("Market Share %", fontsize="20")
axi.legend(loc="upper left",prop={'size': 6})

This produces a massive legend with huge dots.

I know it's because of my sizes variable, but I need that to be there to compare the dots.

My desired output would be dots of a uniform size, with the value.

Here is an example dataset

    Brand   Market Share %  Optimisation Score  Indexed Pages (00s)
brand 1 11  0.4489473684    118
brand 2 2.5 0.22578125  90
brand 3 1.6 0.2321637427    51
brand 4 13.3    0.418783225 215
IDoSeOyO
  • 53
  • 7

2 Answers2

0

You could create a copy of the handles and then set their size. As the handles point to dots inside the plot you can't change their size directly without also changing the dots in the plot.

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import copy

df = pd.DataFrame({"Brand": ["brand 1", "brand 2", "brand 3", "brand 4"],
                   "Market Share %": [11, 2.5, 1.6, 13.3],
                   "Optimisation Score": [0.4489473684, 0.22578125, 0.2321637427, 0.418783225],
                   "Indexed Pages (00s)": [118, 90, 51, 15]})

fig, axi = plt.subplots()
colors = ["blue", "green", "pink", "yellow", "cyan", "orange", "red"]
sizes = 100 * df["Indexed Pages (00s)"]
brand = df["Brand"]
x = df["Optimisation Score"].to_numpy()
y = df["Market Share %"].to_numpy()
for i in range(len(x)):
    axi.scatter(x[i], y[i], color=colors[i], s=sizes[i], alpha=0.4, label=brand[i])

axi.set_xlabel("Optimisation Score", fontsize="20")
axi.set_ylabel("Market Share %", fontsize="20")
handles, labels = axi.get_legend_handles_labels()
handles_new = []
for h in handles:
    hc = copy.copy(h)
    hc.set_sizes([20])
    handles_new.append(hc)
axi.legend(handles_new, labels, loc="upper left")
axi.margins(0.25)  # extra large margins to fit the large scatter dots
plt.tight_layout()
plt.show()

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66
0

It can be adjusted by legend() with 'markerscale'.

axi.legend(loc="upper left", prop={'size': 20}, markerscale=0.1)

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32