【问题标题】:How do I show the "X" axis scale in hours, minutes and seconds in Python?如何在 Python 中以小时、分钟和秒显示“X”轴刻度?
【发布时间】:2020-02-29 04:55:04
【问题描述】:

根据Create a new table in Python用户titusarmah99https://stackoverflow.com/users/8363478/titusarmah99使用Python字典转换数据

import datetime
import numpy as np
import seaborn as sb 
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use("ggplot")


%matplotlib inline 


%config InlineBackend.figure_format='svg'}

读取 Sandvik.log 和 Iscar.log 文件。

            data=[]
        with open('Sandvik.log','r') as file:
            for row in file:
                data.append(row.rstrip('\n').split('|'))
        columns =['DateTime','Xload']

        data_dic = []
        for row in data:
            tmp ={}
            tmp['DateTime']=row[0]
            for i in range(1,len(row)-1):
                if row[i] in columns:
                    tmp[row[i]]=row[i+1]
            for c in columns:
                if c not in tmp:
                    tmp[c] = '' #for rows which donot have the property
            data_dic.append(tmp)

            dfs = pd.DataFrame(data_dic)
        print (dfs.dtypes)



    # Reading Iscar.log    

    data=[]
    with open('Iscar.log','r') as file:
        for row in file:
            data.append(row.rstrip('\n').split('|'))
    columns =['DateTime','Xload']

    data_dic = []
    for row in data:
        tmp ={}
        tmp['DateTime']=row[0]
        for i in range(1,len(row)-1):
            if row[i] in columns:
                tmp[row[i]]=row[i+1]
        for c in columns:
            if c not in tmp:
                tmp[c] = '' #for rows which donot have the property
        data_dic.append(tmp)

        dfi = pd.DataFrame(data_dic)
    print (dfi.dtypes) 


    # Converting the Xload and Datetime variables
    dfs['Xload']=pd.to_numeric(dfs.Xload)

    dfs['DateTime']= pd.to_datetime(dfs['DateTime']) 

    dfi['Xload']=pd.to_numeric(dfi.Xload)

    dfi['DateTime']= pd.to_datetime(dfi['DateTime']) 


# removing null data
dfs.dropna(inplace=True)
dfi.dropna(inplace=True)


# Reset the DataFrame
dfs.reset_index(drop=True, inplace=True)
dfi.reset_index(drop=True, inplace=True)

绘制 Sandvik DataFrame 的 Xload 变量。

dfs.plot('DateTime', color = "red", figsize = (8, 6))

plt.ylim(0,100) # scale up to 100% for Y axis

# creating subtitles
plt.legend(['Sandvik'], loc='upper left') 
plt.title("Machining Time vs. Xload Power")
plt.xlabel("Machining Time")
plt.ylabel("% in Xload variable")

Dataframe Sandvik Chart

绘制 Iscar DataFrame 的 Xload 变量

dfi.plot('DateTime', color = "royalblue", figsize = (8, 6))

plt.ylim(0,100)

# creating subtitles
plt.legend(['Iscar'], loc='upper left') 
plt.title("Machining Time vs Xload Power")
plt.xlabel("Machining Time")
plt.ylabel("% in Xload variable")

Dataframe Iscar Chart

在连接两个图表后,我无法将小时、分钟和秒缩放到“X”轴。

plt.figure(figsize = (10, 6))

for frame in [dfs, dfi]:
    plt.plot(frame['Xload'])


#plt.xlim()
plt.ylim(0,100)

# Criando as legendas
plt.legend(['Sandvik', 'Iscar'], shadow=True, loc='upper left') 
plt.title("Machining Time vs Xload Power")
plt.xlabel("Machining Time")
plt.ylabel("% in Xload variable")

Grouped Charts

我只会以秒为单位使用刻度 dt.strftime ('%S')。 我需要叠加图表(Sandvik 和 Iscar)并每 5 秒更改有序的 X 轴刻度。

dfs['DateTime'] = dfs['DateTime'].dt.strftime('%S') 
dfi['DateTime'] = dfi['DateTime'].dt.strftime('%S')

# overlapping graphics
plt.figure(figsize = (10, 4))
for frame in [dfs, dfi]:
    plt.plot(frame['Xload'])
    plt.legend(['Sandvik', 'Iscar'], loc='upper left') #plot da legend

#plt.xlim()
plt.ylim(0,100)


# using seaborn
x1 = dfs['DateTime']
x2 = dfi['DateTime']
y1 = dfs['Xload']
y2 = dfi['Xload']

f, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, sharey=True, figsize=(10,4))
ax = sns.lineplot(x=x1, y=y1, ax=ax1, color='blue', label='Sardvik', ci=None)
ax = sns.lineplot(x=x2, y=y2, ax=ax2, color='red', label='Iscar', ci=None)

ax1.set_xlim(min(x1), max(x1))
ax2.set_xlim(min(x2), max(x2))
ax1.set_xlabel('Machine Time')
ax2.set_xlabel('Machine Time')
ax1.set_ylabel('% in Xload variable')
ax1.set_xticks(ax1.get_xticks()[::5])
ax2.set_xticks(ax2.get_xticks()[::5])
plt.setp( ax1.xaxis.get_majorticklabels(), rotation=90 )
plt.setp( ax2.xaxis.get_majorticklabels(), rotation=90 )

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    请编辑问题以添加更多信息。尽量不要将其发布为答案。

    您可能已经注意到,Sardvik.logIscar.log 中用于绘图的时间戳彼此相差大约 10 分钟。

    plt.figure(figsize = (20, 6))
    for frame in [dfs, dfi]:
        plt.plot(frame['DateTime'],frame['Xload'])
    
    #plt.xlim()
    plt.ylim(0,100)
    
    # Criando as legendas
    plt.legend(['Sandvik', 'Iscar'], shadow=True, loc='upper left') 
    plt.title("Machining Time vs Xload Power")
    plt.xlabel("Machining Time")
    plt.ylabel("% in Xload variable")
    

    上面的代码产生,它保留了时间戳,但看起来不太好。 如果这解决了问题,那就太好了,但只是为了更好的可视化,您可以将它们绘制为子图 (see example) 或 broken axes using seaborn

    # adding these two lines before removing null
    dfs['DateTime'] = dfs['DateTime'].dt.strftime('%H:%M:%S.%f') 
    dfi['DateTime'] = dfi['DateTime'].dt.strftime('%H:%M:%S.%f')
    
    # using seaborn
    x1 = dfs['DateTime']
    x2 = dfi['DateTime']
    y1 = dfs['Xload']
    y2 = dfi['Xload']
    
    f, (ax1, ax2) = plt.subplots(ncols=2, nrows=1, sharey=True, figsize=(10,6))
    ax = sns.lineplot(x=x1, y=y1, ax=ax1, color='blue', label='Sardvik', ci=None)
    ax = sns.lineplot(x=x2, y=y2, ax=ax2, color='red', label='Iscar', ci=None)
    
    ax1.set_xlim(min(x1), max(x1))
    ax2.set_xlim(min(x2), max(x2))
    ax1.set_xlabel('Machine Time')
    ax2.set_xlabel('Machine Time')
    ax1.set_ylabel('% in Xload variable')
    ax1.set_xticks(ax1.get_xticks()[::10])
    ax2.set_xticks(ax2.get_xticks()[::10])
    plt.setp( ax1.xaxis.get_majorticklabels(), rotation=70 )
    plt.setp( ax2.xaxis.get_majorticklabels(), rotation=70 )
    
    f.suptitle('Machining Time vs Xload Power')
    plt.subplots_adjust(wspace=.01, hspace=0)
    

    以上代码给出

    【讨论】:

    • 这个带有 subplots 的演示文稿非常好,但我仍然需要 覆盖 图形(Sandvik 和 Iscar)并更改 X 轴刻度每 5 秒
    • 您的 Sandvik 和 Iscar 没有相同的 xaxis 值,但我们可以叠加,如图所示 herehere
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 2015-07-21
    • 2014-04-08
    • 1970-01-01
    相关资源
    最近更新 更多