controlling the x ticks date values

前端 未结 2 1133
故里飘歌
故里飘歌 2021-01-11 16:27

I have the following data sample as x,y pairs and both x and y are Unix time-stamps:

1354648326,1354648326
1354649456,1371775551
1354649664,1429649819
135464         


        
相关标签:
2条回答
  • 2021-01-11 16:58

    Limits of your x-axis data is only from 2012-12-05 06:12:06 to 2012-12-05 08:22:19. You have to expand date range.

    However you may use this code to set x-axis ticks every 3 month:

    import matplotlib.pyplot as plt
    from itertools import izip
    import datetime
    import numpy as np
    import pandas as pd
    
    def grouped(iterable, n):
        return izip(*[iter(iterable)]*n)
    
    def getLabels(s,t):
        labels =[]
        for x in pd.date_range(start=s, end=t, freq='3M'):
            labels.append(x.strftime("%Y-%m-%d"))
        print labels
        return labels
    
    arr = [1354648326,1354648326,
    1354649456,1371775551,
    ...
    1354655889,1426675579,
    1354656139,1420486774]
    
    # convert timestamps to datetime objects
    X = list()
    Y = list()
    for x, y in grouped(arr, 2):
        X.append(datetime.datetime.fromtimestamp(x))
        Y.append(datetime.datetime.fromtimestamp(y))
    
    # range of X list is only one day: 2012-12-05
    # you have to enlarge data of X
    print np.min(X),np.max(X)
    
    # sample data
    data = np.random.uniform(-10, 10, size=len(X)*len(Y))
    
    # plot
    plt.scatter(X, Y, s = data)
    ax = plt.gca()
    # set limits for X-axis
    ax.set_xlim([np.min(X),np.max(X)])
    # generate labels
    xlabels = getLabels(np.min(X),np.max(X))
    # set ticks and labels
    ax.set_xticks(xlabels)
    ax.set_xticklabels(xlabels,rotation=20)
    
    plt.show()
    

    If I expand x-axis limits I get something like this on your data:

    ...
    # plot
    plt.scatter(X, Y, s = data)
    ax = plt.gca()
    # set limits for X-axis
    xmin = datetime.datetime(2012,1,1,0,0,0) # np.min(X)
    xmax = xmin + datetime.timedelta(days = 360) # np.max(X)
    ax.set_xlim([xmin, xmax])
    # generate labels every 3 month
    xlabels = getLabels(xmin, xmax)
    # set ticks and labels
    ax.set_xticks(xlabels)
    ax.set_xticklabels(xlabels,rotation=20)
    plt.show()
    

    If you want more complicated datetime tick labels read this answer.

    0 讨论(0)
  • Your problem is that your graph only has five ticks, so it can only display five labels. If you want to display all the labels, then you need to make sure that you have the same number of ticks.

    I don't have pandas installed, and anyway, don't have the full data so can't re-create the labels. I have simply copied the list of labels you have provided. I have also 'reverse-engineered' the min & max for the x-axis from the labels (so that the data plots in the right place).

    This line: ax.xaxis.set_ticks(np.arange(min_x, max_x, int((max_x-min_x)/len(labels)))) Ensures that you have the same number of ticks as labels.

    Note that I have also changed the horizontal alignment of the labels so that, even when squashed up, it is still clear which tick the label corresponds to. This slice of the data appears to plot in the right location, so I'm pretty sure the labels are in the right place.

    (Obviously the y-axis can be treated in the same way)

    import matplotlib.pyplot as plt
    import numpy as np
    import time
    import datetime
    
    labels =['2012-06-30', '2012-09-30', '2012-12-31', '2013-03-31',
             '2013-06-30', '2013-09-30', '2013-12-31', '2014-03-31',
             '2014-06-30', '2014-09-30', '2014-12-31', '2015-03-31',
             '2015-06-30', '2015-09-30', '2015-12-31', '2016-03-31']
    x = []
    y = []
    with open('data.txt','r') as myfile:
        for line in myfile:
            _x, _y = line.strip().split(',')
            x.append(int(_x))
            y.append(int(_y))
    
    min_x = int(time.mktime(datetime.datetime.strptime('2012-06-30','%Y-%m-%d').timetuple()))
    max_x = int(time.mktime(datetime.datetime.strptime('2016-03-31','%Y-%m-%d').timetuple()))
    
    print (datetime.datetime.fromtimestamp(min(x)).strftime('%Y-%m-%d')) 
    # Confirm that we are plotting in the right place for this sample
    
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    ax.set_xlim(min_x, max_x)
    ax.xaxis.set_ticks(np.arange(min_x, max_x, int((max_x-min_x)/len(labels))))
    ax.set_xticklabels(labels, rotation=20, horizontalalignment = 'right')
    ax.scatter(x,y)
    plt.show()
    

    0 讨论(0)
提交回复
热议问题