0

I've been learning how to make scatter plots with groups, and I'm using this tutorial as a reference. I'm currently trying to create this scatter plot, however, I've noticed there is no indentation in line 19 in the code:

import numpy as np
import matplotlib.pyplot as plt

# Create data
N = 60
g1 = (0.6 + 0.6 * np.random.rand(N), np.random.rand(N))
g2 = (0.4+0.3 * np.random.rand(N), 0.5*np.random.rand(N))
g3 = (0.3*np.random.rand(N),0.3*np.random.rand(N))

data = (g1, g2, g3)
colors = ("red", "green", "blue")
groups = ("coffee", "tea", "water")

# Create plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, axisbg="1.0")

for data, color, group in zip(data, colors, groups):
x, y = data
ax.scatter(x, y, alpha=0.8, c=color, edgecolors='none', s=30, label=group)

plt.title('Matplot scatter plot')
plt.legend(loc=2)
plt.show()

and I receive the following error messsage:

  File "<ipython-input-2-58c0796c9f65>", line 19
    x,y=data
    ^
IndentationError: expected an indented block

Therefore, I indented line 19, as such:

for data, color, group in zip(data, colors, groups):
    x, y = data
ax.scatter(x, y, alpha=0.8, c=color, edgecolors='none', s=30, label=group)

but I get AttributeErrors after running the code.

As a reference, I've been using the first batch of code in Joe Kington's superb answer in this question Scatter plots in Pandas/Pyplot: How to plot by category, and followed the indentation pattern, but I'm lost with my scatter plot. Where did I go wrong here?

BigBen
  • 46,229
  • 7
  • 24
  • 40
Jessie
  • 65
  • 7
  • 2
    Indent the `ax.scatter(x, y, ...)` line too? – BigBen Jul 20 '21 at 15:33
  • 1
    Basically, everything which must be in a loop is indented one level higher. It seems the scatter line must be in the loop (color, group are from the for loop) => You should indent it too. – Metapod Jul 20 '21 at 15:37

1 Answers1

2

You must also indent the next line (ax.scatter(x, y, alpha=0.8, c=color, edgecolors='none', s=30, label=group). The following code should work:

import numpy as np
import matplotlib.pyplot as plt

# Create data
N = 60
g1 = (0.6 + 0.6 * np.random.rand(N), np.random.rand(N))
g2 = (0.4+0.3 * np.random.rand(N), 0.5*np.random.rand(N))
g3 = (0.3*np.random.rand(N),0.3*np.random.rand(N))

data = (g1, g2, g3)
colors = ("red", "green", "blue")
groups = ("coffee", "tea", "water")

# Create plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

for data, color, group in zip(data, colors, groups):
    x, y = data
    ax.scatter(x, y, alpha=0.8, c=color, edgecolors='none', s=30, label=group)
    
plt.title('Matplot scatter plot')
plt.legend(loc=2)
plt.show()
matheubv
  • 166
  • 1
  • 7