changing the colour based on the graphs positions matplotlib

独自空忆成欢 提交于 2021-01-29 17:24:27

问题


With the dataset below i am trying to plot a line graph on matplotlib. I am trying to make a function that looks at the previous number and checks whether the current number is higher. If the current function is bigger it would draw a blue line going to the next point such as it would draw a blue line between (1,100) and (2,9313). If its not greater (6,203542) and (7,203542), a red line would be drawn.

import matplotlib.pyplot as plt

x_long = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
L_Amount_list = [100.00, 9313.38, 43601.28, 61701.69, 74331.88, 198913.81, 153054.54, 119162.10, 74382.25, 203542.82, 160774.71, 220307.19, 366459.26]
plt.plot(x_long,L_Amount_list, color = 'green')

回答1:


First, create a list of line colors for the graph with thresholds. Next, instead of drawing the graph one at a time, extract the data two at a time and set the list of colors.

import matplotlib.pyplot as plt

x_long = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
L_Amount_list = [100.00, 9313.38, 43601.28, 61701.69, 74331.88, 198913.81, 153054.54, 119162.10, 74382.25, 203542.82, 160774.71, 220307.19, 366459.26]

colors = ['b' if a < b else 'r' for a,b in zip(L_Amount_list,L_Amount_list[1:])]      

for i in range(len(x_long)):
    try:
        plt.plot(x_long[i:i+2], L_Amount_list[i:i+2], color=colors[i])
    except:
        break
        
plt.show()



来源:https://stackoverflow.com/questions/65453559/changing-the-colour-based-on-the-graphs-positions-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!