2

I am trying to make a scatter plot with this dictionary

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}

I want the keys to be in X-axis and the values to be on Y-axis, and also to show a legend with different key values. I have tried this code-

import matplotlib.pyplot as plt

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}
colors = list("rgbk")
x, y =[], []
for i in d.keys():
   for j in d[i]:
       x.append(i)
       y.append(j)
   plt.scatter(x, y, color = colors.pop())
   plt.legend(d.keys())
plt.show()

But this is giving me a plot with points with only one colour but the legends are alright.

This is the output image that I am getting

3 Answers 3

3

It's better to use plt.subplots() in this case, so you can reuse the same axis. The colour iteration comes for free but I left it in, not sure if you prefer rgbk.

When possible, avoid for-loops in Python for better readability and performance.

import matplotlib.pyplot as plt

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}
colors = list("rgbk")

fig, ax = plt.subplots()

for x, ys in d.items():
    ax.scatter([x] * len(ys), ys, color = colors.pop(), label=x)

plt.legend()
plt.show()

plot

If you are dealing with large arrays, consider using numpy. In this case you can rescale the key for example like this:

import matplotlib.pyplot as plt
import numpy as np

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}
colors = list("rgbk")

fig, ax = plt.subplots()

for x, ys in d.items():
    ax.scatter(np.full_like(ys, x), ys, color = colors.pop(), label=x)

plt.legend()
plt.show()
Sign up to request clarification or add additional context in comments.

Comments

2

You initialize the x and y lists before the loop. In each iteration, you add new values to the list, and they overpaint the old points. Move the line x, y =[], [] into the loop.

1 Comment

Also put plt.legend(d.keys()) outside the loop
0

Here's a way:

import matplotlib.pyplot as plt

d = {1: [1, 2, 3, 4, 5], 3: [3, 6, 9, 12, 15], 5: [5, 10, 15, 20, 25]}

for i in d.keys():
   for j in d[i]:
       plt.scatter(i,j,color=(i/10,i/10,i/10))
   plt.legend(d.keys())
plt.show()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.