0

I am trying to plot a single line graph with different color (positive value: blue, negative value: red) There is a csv file which is updating data continuously, I am reading the data and update the graph when a new value is enter to that csv file.

Below are my code and the result.


def main():
    plt.style.use('fivethirtyeight')

    fig = plt.figure()
    fig.set_figheight(4)
    fig.set_figwidth(8)

    def animate(i):
        data = pd.read_csv('data.csv')
        if len(data['y']) > 200:
            x = list(range(200))
            y = data['y'][-200:]
        else:
            x = list(range(len(data['y'])))
            y = data['y']
        
        fig.clf()
        
        # Adds subplot on position 1.
        ax = fig.add_subplot(211)

        # Set value to subplot pos 2.
        ax.plot(x, y))
        #ax.scatter(x, y, c=y, cmap='Reds')
       
        plt.tight_layout()

    ani = FuncAnimation(fig, animate, interval=0.00001)

    plt.tight_layout()
    plt.show()

enter image description here

How can I change the color of the line to red when the value is negative?

yen ng
  • 69
  • 1
  • 1
  • 4
  • 1
    1) A Line2D object has exactly one color - you have to create subsets of blue and red lines stored in a LineCollection or list. See, for instance, [here](https://stackoverflow.com/a/44649053/8881141) or [here](https://stackoverflow.com/a/65181776/8881141) 2) Your current approach of clearing and redrawing the entire figure is not what FuncAnimation is created for. Usually, one defines objects like a Line2D object outside the animation function and only updates changing parameters like x-y data, color, etc. – Mr. T Mar 11 '22 at 18:25
  • 1
    See [Red line when data is negative and green line when data is positive](https://stackoverflow.com/questions/48236622/red-line-when-data-is-negative-and-green-line-when-data-is-positive-in-pandas) – JohanC Mar 11 '22 at 19:20

0 Answers0