Home > other >  How to color different segments of plotted curve based on value? [python]
How to color different segments of plotted curve based on value? [python]

Time:06-11

I am trying to figure out how to plot a dataframe column where the color of the line changes based on its value, but I am stuck on how to get these values referenced.

For example, I have this dataframe:

    Timestamp    Value
-------------------------
0       5:00         4
1       5:01         5
2       5:02         8
3       5:03        12
4       5:04        13
5       5:05         2
...

I simple run some form of:

df.plot(x="Timestamp", y=["Value"], figsize=(9, 8)) 

to get a plot of the values changing over time.

Now, I have my values separated into different categories/bins, where: 0-5 = "Low", 6-15 = "Mid" and 16 = "High". I want to have my same plot, but now with all values on the curve corresponding to "Low" to be blue, corresponding to "Mid" to be green, and corresponding to "High" to be red. So I will see see a single curve plotted, made up from the "Value" column, but segmented into different colors based on value. How can I accomplish this in python? I am confused about how to set up an index/key for translating values to colors and what argument is needed in .plot() to actually have color based on value.

CodePudding user response:

Given this:

index Timestamp Value
0 5:00 3
1 5:01 4
2 5:02 5
3 5:03 13
4 5:04 14
5 5:05 15
6 5:06 17
7 5:07 18
8 5:08 19

Then:

x = df.Timestamp
y = df.Value

for x1,x2, y1,y2 in zip(x, x[1:], y, y[1:]):
  if (0<=y1) & (y1<=5):
    plt.plot([x1, x2], [y1, y2], 'b')
  elif (6<=y1) & (y1<=15):
    plt.plot([x1, x2], [y1, y2], 'g')
  else:
    plt.plot([x1, x2], [y1, y2], 'r')

plt.show()

Output:

enter image description here

  • Related