集成日期范围,并标记X轴

2024-04-27 04:34:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图整合两条曲线,因为他们随着时间的变化使用熊猫。我正在从CSV文件加载数据,如下所示:

Example of pandas table from CSV

其中日期是X轴,油点和水点都是Y轴。我已经学会了使用横截面选项来隔离“NAME”值,但是很难找到一个好的方法来将日期作为X轴进行集成。我最终希望能够得到两条曲线的积分,并将它们相互叠加。我也有麻烦的绘图默认的x记号任意值,而不是日期。你知道吗

Image of pyplot with Oil/Water curves

我可以手动更改标签/记号,但有一个大的CSV处理,并希望自动化的过程。任何帮助都将不胜感激。你知道吗

姓名、日期、O、W

A,2000年1月20日,12月50日

B,2000年1月20日,25日,28日

C,2000年1月20日,14日,15日

A,2000年1月21日,34,50

B,2000年1月21日,8月3日

C,2000年1月21日,10月19日

A,2000年1月22日,47,35

B,2000年1月22日,4月27日

C,2000年1月22日,46,1

A,2000年1月23日,19日,31日

B,2000年1月23日,18日,10日

C,2000年1月23日,19日,41日

以上文本形式的CSV内容。你知道吗


Tags: 文件csv数据方法name绘图选项时间
2条回答

除了我上面的评论之外,下面是一些示例代码(使用前面提到的example中的逻辑)用格式化日期标记xaxis。希望这有帮助。你知道吗

数据收集/导入:

只是为示例重新创建数据集。你知道吗

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

header = ['NAME', 'DATE', 'O', 'W']
data = [['A','1/20/2000',12,50],
        ['B','1/20/2000',25,28],
        ['C','1/20/2000',14,15],
        ['A','1/21/2000',34,50],
        ['B','1/21/2000',8,3],
        ['C','1/21/2000',10,19],
        ['A','1/22/2000',47,35],
        ['B','1/22/2000',4,27],
        ['C','1/22/2000',46,1],
        ['A','1/23/2000',19,31],
        ['B','1/23/2000',18,10],
        ['C','1/23/2000',19,41]]

df = pd.DataFrame(data, columns=header)
df['DATE'] = pd.to_datetime(df['DATE'], format='%m/%d/%Y')

# Subset to just the 'A' labels.
df_a = df[df['NAME'] == 'A']

绘图:

# Define the number of ticks you need.
nticks = 4
# Define the date format.
mask = '%m-%d-%Y'

# Create the set of custom date labels.
step = int(df_a.shape[0] / nticks)
xdata = np.arange(df_a.shape[0])
xlabels = df_a['DATE'].dt.strftime(mask).tolist()[::step]

# Create the plot.
fig, ax = plt.subplots(1, 1)
ax.plot(xdata, df_a['O'], label='Oil')
ax.plot(xdata, df_a['W'], label='Water')
ax.set_xticks(np.arange(df_a.shape[0], step=step))
ax.set_xticklabels(xlabels, rotation=45, horizontalalignment='right')
ax.set_title('Test in Naming Labels for the X-Axis')
ax.legend()

输出:

enter image description here

我建议将X轴修改为某种形式的整数或浮点数(从某个时间开始的秒、分钟、小时、天,基于您需要的精度)。然后可以使用常规方法进行积分,x轴将不再默认为其他值。你知道吗

How to convert datetime to integer in python

相关问题 更多 >