python - matplotlib graph fill 2 colors above and below axis -
i have line graph partly above , below x-axis of 0
. how can color area above line green, , below red? here's code:
hydropathy_dict = {"i":-0.528, "l":-0.342, "f":-0.370, "v":-0.308, "m":-0.324, "p":-0.322, "w": -0.270, "h": 2.029, "t": 0.853, "e": 3.173, "q": 2.176, "c": 0.081, "y": 1.677, "a":-0.495, "s": 0.936, "n": 2.354, "d": 9.573, "r": 4.383, "g": 0.386, "k": 2.101 } seq = 'chcrrscysteysygtctvmginhrfcc' hydropathy_list = [] plot_x_axis = [] aa in seq: hydropathy_list.append(hydropathy_dict[aa]) print(acc,hydropathy_list) in range(len(hydropathy_list)): plot_x_axis.append(i) plt.plot(plot_x_axis,hydropathy_list) plt.plot([0,len(hydropathy_list)],[0,0]) plt.show()
try this:
import matplotlib.pyplot plt import numpy np scipy import interpolate hydropathy_dict = {"i":-0.528, "l":-0.342, "f":-0.370, "v":-0.308, "m":-0.324, "p":-0.322, "w": -0.270, "h": 2.029, "t": 0.853, "e": 3.173, "q": 2.176, "c": 0.081, "y": 1.677, "a":-0.495, "s": 0.936, "n": 2.354, "d": 9.573, "r": 4.383, "g": 0.386, "k": 2.101 } seq = 'chcrrscysteysygtctvmginhrfcc' hydropathy_list = [] plot_x_axis = [] aa in seq: hydropathy_list.append(hydropathy_dict[aa]) #print(seq, hydropathy_list) in range(len(hydropathy_list)): plot_x_axis.append(i) # convert np array hydropathy_list = np.array(hydropathy_list) plot_x_axis = np.array(plot_x_axis) # densify data filled color plot f = interpolate.interp1d(plot_x_axis, hydropathy_list) xnew = np.arange(plot_x_axis[0], plot_x_axis[-1], 0.1) ynew = f(xnew) plt.plot(plot_x_axis, hydropathy_list) # blue line plt.plot([0, len(hydropathy_list)], [0,0]) # green line # use xnew, ynew plot filled-color graphs plt.fill_between(xnew, 0, ynew, where=(ynew-1) < -1 , color='red') plt.fill_between(xnew, 0, ynew, where=(ynew-1) > -1 , color='green') plt.show()
edit
(in response of questions in comment)
statement where=(ynew-1)<-1
inside fill_between()
requires ynew
numpy array (simple list won't work).
scipy.interpolate() used more points along curve, that, color fills target areas completely.
with original points, result looks this:
Comments
Post a Comment