dips_99
dips_99

Reputation: 23

Plotting multiple values to one key in python

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

Upvotes: 2

Views: 1166

Answers (3)

tamasgal
tamasgal

Reputation: 26259

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()

Upvotes: 3

Red
Red

Reputation: 27557

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()

Upvotes: 0

DYZ
DYZ

Reputation: 57033

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.

Upvotes: 2

Related Questions