英文:
How to plot dates on the x-axis after splitting the splitting the graph in positve and negative?
问题
我正在尝试创建一条折线图,当数据为负时为红色,当数据为正时为绿色,如这篇帖子中建议的。这是通过将数据框拆分为正数和负数并分别绘制来实现的。使用以下代码实现:
plt.figure(figsize=(12,8))
new_df.Performance.where(new_df.Performance.ge(0), np.nan).plot(color='green')
new_df.Performance.where(new_df.Performance.lt(0), np.nan).plot(color='red')
plt.show()
这能正常工作,但我无法在 x 轴上绘制日期,它只会绘制数字。我该如何解决这个问题?
这是数据框的简化版本:
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 |
这里的 'Date' 列是一个日期时间对象。
我尝试过在代码中添加 x = 'date' 和多种变体,但没有成功。
英文:
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:
plt.figure(figsize=(12,8))
new_df.Performance.where(new_df.Performance.ge(0), np.nan).plot(color='green')
new_df.Performance.where(new_df.Performance.lt(0), np.nan).plot(color='red')
plt.show()
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.
答案1
得分: 2
以下是翻译好的内容:
也许这会起作用?
import pandas as pd
import matplotlib.pyplot as plt
# 假设 'Date' 是包含日期的列
new_df['Date'] = pd.to_datetime(new_df['Date']) # 如果尚未转换为日期类型,则将 'Date' 列转换为日期类型
# 将 'Date' 列设置为索引
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.xlabel('Date')
plt.ylabel('Performance')
plt.title('Performance Plot')
plt.legend(['Positive', 'Negative'])
plt.show()
英文:
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.xlabel('Date')
plt.ylabel('Performance')
plt.title('Performance Plot')
plt.legend(['Positive', 'Negative'])
plt.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论