How to plot dates on the x-axis after splitting the splitting the graph in positve and negative?


I am trying to create a line plot which is red when negative and green when positive, as suggested in this post. This is done by splitting the dataframe into positive and negative and plot them individually. This is done using the following code:


    new_df.Performance.where(, np.nan).plot(color='green')
    new_df.Performance.where(, np.nan).plot(color='red')

This works fine, but I am unable to plot the dates on the x- axis. It will only plot numbers. How can I fix this?

Here is a simplified version of the dataframe:

Date            Performance
8/2/2022 0:00   -1.01
8/2/2022 20:00  -0.0001
8/2/2022 20:00  0.0001
8/3/2022 0:00   0.19
8/4/2022 0:00   2
8/6/2022 0:00   0.0001
8/7/2022 0:00   -0.0001
8/8/2022 0:00   -5

Here, the ‘Date column is a datetime object.

I tried adding x = ‘date’ and multiple variation to the code, but it does not work.

Asked By: Yope



Maybe that will work?

import pandas as pd
import matplotlib.pyplot as plt

# Assuming 'Date' is the column containing the dates
new_df['Date'] = pd.to_datetime(new_df['Date'])  # Convert 'Date' column to datetime if it's not already

# Set 'Date' column as the index
new_df.set_index('Date', inplace=True)

new_df.Performance.where(new_df.Performance >= 0, np.nan).plot(color='green')

new_df.Performance.where(new_df.Performance < 0, np.nan).plot(color='red')

plt.title('Performance Plot') 
plt.legend(['Positive', 'Negative'])
Answered By: Riccardo DAndrea
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.