Home > database >  How do I plot list of tuples in Python and change x axis into another array?
How do I plot list of tuples in Python and change x axis into another array?

Time:04-26

Here is my data:

('2022-04-23 14:51', 'customer1', 50, 'red')
('2022-04-23 16:19', 'customer2', 50, 'red')
('2022-04-23 16:20', 'customer2', 50, 'red')
('2022-04-23 16:34', 'customer3', 50, 'red')
('2022-04-23 17:25', 'customer4', 50, 'red')
('2022-04-23 17:37', 'customer5', 50, 'red')
('2022-04-23 18:29', 'customer6', 50, 'red')
('2022-04-23 18:33', 'customer7', 50, 'red')

The x represents time, y represents customer, using this code, I have generated a picture:

import matplotlib.pyplot as plt

plt.scatter(*zip(*qr_dict)) # this is a list of tuples
plt.xlabel('time')
plt.ylabel('customer')
plt.xticks(rotation=270)
plt.subplots_adjust(bottom=0.55)
plt.grid()
plt.show()

However, I want to change x axis into a time span from 2022-04-23 00:00 to 2022-04-23 24:00, and interval is 5 minute, how am I suppose to do that?

CodePudding user response:

Note: '2022-04-23 00:00' and '2022-04-23 24:00' are the same date, so your x axis can be from '2022-04-23 00:00' to '2022-04-24 00:00'.

You can obtain the x axis in this way:

from datetime import datetime, timedelta
import numpy as np

x_start = datetime.strptime('2022-04-23 00:00', "%Y-%m-%d %H:%M")
x_end = datetime.strptime('2022-04-24 00:05', "%Y-%m-%d %H:%M")

timestamps = np.arange(x_start, x_end, timedelta(minutes=5), dtype=datetime)

x_axis = [timestamp.strftime("%Y-%m-%d %H:%M") for timestamp in timestamps]
  • Related