Home > Mobile >  change color according to the axis, matplotlib
change color according to the axis, matplotlib

Time:10-06

graph

In this graph I would like to make everything negative in x to be red, and in y to be green, or just the 3 most negative dots be red and 3 most positive dots be green.

from matplotlib import pyplot as plt

ex_x = [res1,res2,res3,res4,res5,res6,res7,res8,res9,res10,res11,res12,res13,res14,res15,res16,res17,res18,res19,res20,res21,res22,res23,res24,res25,res26,res27,res28,res29,res30,res31,res32,res33,res34,res35,res36,res37,res38,res39,res40,res41,res42,res43,res44,res45,res46,res47]
ex_y = ["1","2","2.1","2.1.1","2.2","3","3.1","3.2","4","4.1","4.1.1","4.1.1A)","4.1.1B)","4.1.2","4.2","4.2A)","4.2B)","4.3","4.4","5","5.1","5.1.1","5.1.2","5.1.2A)","5.1.2B)","5.1.3","5.1.4","5.2","5.2.1","5.2.1A)","5.2.1B)","5.2.1C)","5.2.2","5.2.3","5.2.3A)","5.2.3B)","5.2.4","5.2.5","6","6.1","7","7.1","7.2","8.1","8.1A)","8.1B)","8.2"]

l_x = [0, 0]
l_y = [47, 0]

z_x = [-10, 10]
z_y = [0, 0]

plt.grid(True)

for x in range(-10,10):
    plt.plot(l_x, l_y, color = "k", linewidth = 2)

plt.plot(z_x, z_y, color = 'k', linewidth = 1)
plt.plot(ex_x, ex_y, marker='.')
plt.gca().invert_yaxis()
plt.title("Perfil Neuropsicológico")
plt.tight_layout()
plt.show()

CodePudding user response:

I would recommend to transform the lists ex_x and ex_y to numpy arrays as a first step:

import numpy as np
ex_x = np.array(ex_x)
ex_y = np.array(ex_y)

As a second step, the selection of only positive or negative values is pretty straightforward:

plt.plot(ex_x[ex_x<0], ex_y[ex_x<0], color='red', marker='.', linestyle='none')
plt.plot(ex_x[ex_x>=0], ex_y[ex_x>=0], color='green', marker='.', linestyle='none')

This is one of the perks of numpy arrays!

As you see, I have removed the connecting lines in this example. Having those would be more involved (what would the color of a line between a red and a green dot be?). What you could do, of course, is plot an additional line with all the data in a neutral color, e.g.

plt.plot(ex_x, ex_y, color='dimgrey')

It would be easiest, then, to keep this line in the background by plotting it "before" the other points.


On a side note: I think in the for loop, you plot the same line 20 times.

CodePudding user response:

Some ideas:

import pylab as plt
import numpy as np
# make some test data (np.ndarray types)
y = np.random.random(100)-0.5
x = np.arange(len(y))

plt.plot( x, y)
plt.plot( x[y<0], y[y<0], 'r.') # color negative red
plt.plot( x[y>=0], y[y>=0], 'g.')
order = np.argsort(y)  # order of y sorted from lowest to highest
plt.plot( x[order[:3]], y[order[:3]], 'rs', ms=10, mfc='none')  # lowest 3
plt.plot( x[order[-3:]], y[order[-3:]], 'gs', ms=10, mfc='none')  # highest 3
plt.xlabel("x")
plt.ylabel("y")
plt.show()

sample image

  • Related