2

Lets say I have the following data say

x=[0,1,2,3,4,5,6,7,8,9]
y=[1.0,1.5,2.3,2.2,1.1,1.4,2.0,2.8,1.9,2.0]
z=['A','A','A','B','B','A','B','B','B','B']
plt.plot(x,y, marker='S')

will give me a x-y plot with square markers. Is there a way to change the marker type based on the data z, so that all 'A' type has square marker and 'B' type has a triangle marker.

but I want to add 'z' data on the curve only when it changes from one type to another (in this case from 'A' to 'B' or vice versa)

1 Answer 1

1
import matplotlib.pyplot as plt

fig = plt.figure(0)
x=[0,1,2,3,4,5,6,7,8,9]
y=[1.0,1.5,2.3,2.2,1.1,1.4,2.0,2.8,1.9,2.0]
z=['A','A','A','B','B','A','B','B','B','B']
plt.plot(x,y)

if 'A' in z and 'B' in z:
    xs = [a for a,b in zip(x, z) if b == 'A']
    ys = [a for a,b in zip(y, z) if b == 'A']
    plt.scatter(xs, ys, marker='s')

    xt = [a for a,b in zip(x, z) if b == 'B']
    yt = [a for a,b in zip(y, z) if b == 'B']
    plt.scatter(xt, yt, marker='^')
else:
    plt.scatter(x, y, marker='.', s=0)


plt.show()

Or

import matplotlib.pyplot as plt

fig = plt.figure(0)
x=[0,1,2,3,4,5,6,7,8,9]
y=[1.0,1.5,2.3,2.2,1.1,1.4,2.0,2.8,1.9,2.0]
z=['A','A','A','B','B','A','B','B','B','B']
plt.plot(x,y)

if 'A' in z and 'B' in z:
    plt.scatter(x, y, marker='s', s=list(map(lambda a: 20 if a == 'A' else 0, z)))
    plt.scatter(x, y, marker='^', s=list(map(lambda a: 20 if a == 'B' else 0, z)))
else:
    plt.scatter(x, y, marker='.', s=0)


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

3 Comments

Unfortunately my datapoints are huge (10K), so the scatter points seem to overlap and makes the plot messy. Will this work for simple line plot?
@WanderingMind What do you mean by simple line plot?
yes, but I fixed the issue in scatter plot by changing the figure size and the marker size. I can accept your answer now.

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.