0

I have some data, that I have loaded up into numpy, I do not have a csv or any file loaded up with the range of dates I need, however I know what this array length is.

Currently I am just doing this to print up a simple graph:

t = numpy.arange(0.0, len(data), 1)
pylab.plot(t, data)

Would it be possible to replace t here so that I can specify a start and end date and it would print the actual date? Say, I have 365 days in my dataset, it would give the plot actually dates such as DD/MM/YYYY , 1/1/1999.1/2/1999.....12/31/1999?

1 Answer 1

1

You can pass any list of strings or numbers as the x axis argument to the plot call and it will try to use them for x axis labels. Here is a basic working example showing how to generate a range of dates and use them in the graph. Because two different date formats are used in the question, DD/MM/YYYY and M/D/YYYY, I provided an example of each.

Here is the code:

import matplotlib.pylab as plt
import datetime

# Define some sample data
my_data = [x ** 3 / 100 - 2 * x ** 2 / 10 + x / 2 + 4 for x in range(20)]
# The first date in the data
start_date = datetime.datetime(1999, 1, 1)
# Generate a new date for each subsequent datapoint
dates = [start_date + datetime.timedelta(x) for x in range(len(my_data))]

# Generate the graphs for the two representations described in the questions
for name, x_labels in [
    ('As written', [f'{date.day:02}/{date.month:02}/{date.year:04}' for date in dates]),
    ('As the example', [f'{date.month}/{date.day}/{date.year}' for date in dates]),
]:
    plt.title(name)
    # matplotlib will automatically use the text has the x-axis labels
    plt.plot(x_labels, my_data)
    # Rotate the labels so they are legible without overlapping
    plt.xticks(rotation=60)
    # Re-scale the window so that everything fits
    plt.tight_layout()
    plt.show()

And here are the graphs it generated: Graph showing date strings as x-ticks using format as written

Graph showing date strings as x-ticks using format as shown in the example strings

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.