set_xticks导致图表中的数据被压缩

时间:2019-05-16 14:26:09

标签: python matplotlib

我正在尝试绘制不同频率的数据,我的某些数据为55H,而我拥有的其他数据集为4Hz。

到目前为止,我已经在相同的时间尺度上绘制了所有值,我现在只是尝试设置我的xticks,我对yticks没问题,但是当我尝试设置xticks时,它会导致图挤压图片。

下面的代码是我用来绘制数据集的函数,它生成了下面的图表。正如您所看到的绿线一样,如果我注释掉

,我的凝视目标就会被压扁。

host.set_xticks(xlables)

我得到了想要的图形,但是没有正确的刻度。

无法真正弄清楚是怎么回事,老实说,由于我一直在努力绘制不同长度的数据,因此代码非常混乱。

非常感谢

import sys
import csv
import os
import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
from math import isclose
import matplotlib.transforms as mtransforms
from functools import reduce
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plticker

# Function for location detection 

# You will need to merge data what ever sensor you are using with the GPS data on timestamp
# Pass your GPS start and end lat and lon and the merged dataframe to the function
def GPS_find_loc(gps_startLat, gps_startLon, gps_endLat, gps_endLon, df): 
    locList = []
    #dfnew = df[['latatude', 'longatude']].copy()
    #dfnew = dfnew.dropna().reset_index(drop=True)
    for index, row in df.iterrows():
        if isclose(row['latitude'], gps_startLat, abs_tol=1e-4) == True and isclose(row['longitude'], gps_startLon, abs_tol=1e-4) == True:
            locList.append(index)

        elif isclose(row['latitude'], gps_endLat, abs_tol=1e-4) == True and isclose(row['longitude'], gps_endLon, abs_tol=1e-4) == True:
            locList.append(index)
    Start = locList[0]
    End = locList[-1]
    return Start, End

def plotGaze(Loc, lat, lon, Par, location):

    time = df.timestamp[lon] - df.timestamp[lat]


    fig = plt.figure(figsize=(15,7.5))
    host = fig.add_subplot(111)

    par1 = host.twinx()
    par2 = host.twinx()
    par3 = host.twinx()

    host.set_xlabel("Time (s)")
    host.set_ylabel("Gaze targets")
    par1.set_ylabel("Pressure on Acc (bar)")
    par2.set_ylabel("Pressure (bar)")
    par3.set_ylabel("HR")

    color1 = "g"
    color2 = "b"
    color3 = "y"
    color4 = "r"

    x1 = np.linspace(0, 1, len(df.objectName[lat:lon].dropna().reset_index(drop=True)))
    x3 = np.linspace(0, 1, len(df.HR[lat:lon].dropna().reset_index(drop=True)))

    mean = np.mean(df.HR.dropna().reset_index(drop=True))


    p1, = host.plot(x1, df.objectName[lat:lon].dropna().reset_index(drop=True), label='Object', color='g', linewidth=0.5)

    p2, = par1.plot(x1, df.pressureOnAccPeddle[lat:lon].dropna().reset_index(drop=True).rolling(13).median(), label='Acc pedel', color='b', linewidth=0.5)

    p3, = par2.plot(x1, df.pressure[lat:lon].dropna().reset_index(drop=True).rolling(13).median(), label='Acc pedel', color='y', linewidth=0.5)
# df.HR is at a lower frequency 
    p4, = par3.plot(x3, df.HR[lat:lon].dropna().reset_index(drop=True), label='Acc pedel', color='r', linewidth=0.5)

    par3.axhline(y=mean, label='Mean= ' + format(round(mean, 1)), color='r', linestyle='--', linewidth=0.5)

    lns = [p1, p2, p3, p4]

# Setting outer spines
    par2.spines['right'].set_position(('outward', 90))  
    par3.spines['right'].set_position(('outward', 40))     


    xlables = np.arange(0, time)

    host.set_xticks(xlables)

    host.set_xticklabels(xlables, fontsize='small')



    labels = [item.get_text() for item in host.get_yticklabels()]
    labels = ('IVI','Cluster','RearViewMirror','Others','RightSideViewMirror','Right_Others','Windshield','FrontalArea','Left_Others','LeftSideViewMirror')

    host.set_yticklabels(labels, color=color1,fontsize='small')

    #host.set_yticklabels(np.arange(8),('IVI','Cluster','RearViewMirror','Others','RightSideViewMirror','Right_Others','Windshield','FrontalArea','Left_Others','LeftSideViewMirror'))


    #host_subplot.yticks(np.arange(10),('IVI','Cluster','RearViewMirror','Others','RightSideViewMirror','Right_Others','Windshield','FrontalArea','Left_Others','LeftSideViewMirror'))
    host.yaxis.label.set_color(p1.get_color())
    par1.yaxis.label.set_color(p2.get_color())
    par2.yaxis.label.set_color(p3.get_color())
    par3.yaxis.label.set_color(p4.get_color())

    fig.tight_layout() 

file_name_HR = "stackoverflowexample.csv"
pd.set_option('display.float_format', lambda x: '%.6f' % x)
df =  pd.read_csv(file_name_HR, sep=',', header=0) 

LatStartBrown, LonStartBrown =  53.279644, -9.069730
bExitlat, bExitlon = 53.278779, -9.069806
BrownStart, BrownEnd = GPS_find_loc(LatStartBrown, LonStartBrown, bExitlat, bExitlon, df)
df[BrownStart:BrownEnd].to_csv("C:/PhD Tests/Results/stackoverflowexample.csv") 
plotGaze("_Brown.png", BrownStart, BrownEnd, Par, "Brown")

我的声誉不够高,无法发布图片,但是您可以在下面查看

请在下面找到数据 https://drive.google.com/open?id=1zdayM5JWLLYLA_bokaWw8EVLzDRFlQ21

https://i.imgur.com/93ePMWs.png

0 个答案:

没有答案