Reputation: 87
I am trying to plot a simple chart with markers as "x" (green colour) if datapoint is even and "o" (red color) if datapoint is odd. However the chart is rendered with all markers as "o" except the last which is correctly showing as "x". Pls guide.
import matplotlib.pyplot as plt
a = []
b = []
for i in range( 1, 11 ):
a.append( i )
b.append( i )
if ( i % 2 ) == 0:
plt.plot( a, b, "gx" )
else:
plt.plot( a, b, "ro" )
plt.show()
Upvotes: 0
Views: 348
Reputation: 658
If you look carefully, the first markers are not red "o"'s, but red circles with a green "x" inside. The for loop you made is equivalent to:
plt.plot([1], [1], "ro")
plt.plot([1, 2], [1, 2], "gx")
plt.plot([1, 2, 3], [1, 2, 3], "ro")
(...)
As a consequence, you will plot 10 different graphics (technically lines.Lines2D objects). The last object you plot, for i=10, is "gx"; it ends up on top of the others.
Here's a corrected version of your algorithm (make one plot per point):
# Not a good way to go about it
import matplotlib.pyplot as plt
# Loop, one plot per iteration
for i in range(1,11):
if i % 2 == 0:
plt.plot(i, i, "gx")
else:
plt.plot(i, i, "ro")
plt.show()
Here's a better algorithm, though:
# use this one instead
import matplotlib.pyplot as plt
# Generate a, b outside the body of the loop
a = list(range(1,11))
b = list(range(1,11))
# Make one plot per condition branch
# See also https://stackoverflow.com/questions/509211/understanding-slice-notation
plt.plot(a[0::2], b[0::2], "gx")
plt.plot(a[1::2], b[1::2], "ro")
plt.show()
Upvotes: 1