如何从时间戳为x轴的csv数据生成多线图

时间:2017-08-25 12:35:11

标签: python pandas matplotlib

以下是我的CSV格式示例数据(stats_1.csv):

timestamp,ip,CPU,memory
2017-08-24 18:57:40,10.20.6.181,46,14
2017-08-24 18:57:50,10.20.6.182,43,12
2017-08-24 19:07:40,10.20.6.181,46,14
2017-08-24 19:07:50,10.20.6.182,43,12
2017-08-24 19:17:40,10.20.6.181,46,14
2017-08-24 19:17:50,10.20.6.182,43,12
2017-08-24 19:27:40,10.20.6.181,46,14
2017-08-24 19:27:50,10.20.6.182,43,12
2017-08-24 19:37:40,10.20.6.181,46,14
2017-08-24 18:37:50,10.20.6.182,43,12

我希望从中获得2D线图,其中X轴为时间戳,Y轴为 CPU(内存将有一个单独的图表)。

在图表中,每个IP和图例应该有一行。

这是我到目前为止所尝试的:

import matplotlib.pyplot as plt
import pandas

# setup the dataframe
data_frame = pandas.read_csv("stats_1.csv")

def plot_cpu_utilization_graphs(df):
    column_name = 'CPU'
    df = df[[column_name, 'timestamp', 'ip']]
    max_value = df[column_name].max()
    if max_value < 100:
        max_value = 100
    min_value = df[column_name].min()
    if min_value > 0:
        min_value = 0
    start_idx = df['timestamp'].iloc[0]
    end_idx = df['timestamp'].iloc[-1]
    time_series = pandas.DatetimeIndex(freq='10T', start=start_idx, end=end_idx)
    y_axes_series = range(min_value, max_value, 10)
    #ax = df.groupby('ip').plot(x='timestamp', y='CPU')
    fig, ax = plt.subplots(1, 1)
    df.groupby("ip").plot(x='timestamp', y='CPU', ax=ax)
    ax.set_xlim(time_series[0], time_series[-1])
    ax.set_ylim(min_value, max_value)
    plt.show()



plot_cpu_utilization_graphs(data_frame)

这就是我得到的:enter image description here

1 个答案:

答案 0 :(得分:0)

将时间戳列转换为日期时间格式,然后它应该起作用:

df['timestamp'] = pd.to_datetime(df['timestamp'])