format xaxis values with time and show them only under the scatter plot value using matplotlib in Python

StackOverflow https://stackoverflow.com/questions/22132732

  •  19-10-2022
  •  | 
  •  

Question

I am plotting a scatter plot and need help with formatting the xaxis values. Below is my code.

import matplotlib.pyplot as plt
import matplotlib
import numpy as np 
import time
d ={'5000cca234c1c445': {382877: 7, 382919: 3},
'5000cca234c94a2e': {382873: 1, 382886: 1},
'5000cca234c89421': {383173: 1, 383183: 2, 382917: 1, 382911: 1},
'5000cca234c5d43a': {382889: 1, 382915: 1, 382917: 8},
'5000cca234c56488': {382909: 2, 382911: 5}}

colors = list("rgbcmyk")

for data_dict in d.values():
    x = data_dict.keys()
    y = data_dict.values()
    plt.scatter(x,y,color=colors.pop(),s = 60)
    plt.ylabel("Errors" , fontsize=18, color="Green")
    plt.xlabel("Occured at",fontsize=18, color="Green")
    plt.title("DDN44a" , fontsize=25, color="Blue")
    plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)
    plt.xticks(rotation='vertical') 
#plt.ylim(min(y),max(y))
plt.grid()

plt.legend(d.keys())
plt.show()

the x-axis values( 382873,382866,382873.......) are converted dates using "mktime" function by following line of code.

bin = int(mktime(dt) / 3600)

(I am trying to see how many time does the error occur in one hour) On the graph, x-axis values are shown as 382873,382866,382873..etc. I want them to convert them back to the dates(with MM/DD/YY MM:HH:SS FORMAT) they represent. Also I want the date to show directly below the scatter plot (dot) with same color as the dot.

Any help will be greatly appreciated.

No correct solution

OTHER TIPS

You should convert your dates into datetime.datetime objects and use them for your xaxis instead of your number for the time. Use a DateFormatter to get the desired format.

This gives you April 3rd, 2012, 17:30 15 seconds with format:

import datetime
d = datetime.datetime(2012, 4, 3, 17, 30, 15)
print(d.strftime('%m/%d/%y %M:%H:%S'))

04/03/12 30:17:15

DateFormatter takes the same formatting string.

Have a look at annotations for putting the dates below the dots.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top