0

I am trying to alter the x-ticks on the plot below. When I run the code below I'm getting an error:

ValueError: unit abbreviation w/o a number

I can't seem to find anything on this except it's related to pd.to_timedelta. However, I can't find any solutions on this.

I've upgraded all relevant packs including matplotlib.

import pandas as pd
import matplotlib.pyplot as plt

d = ({
    'A' : ['08:00:00','08:10:00','08:12:00','08:26:00','08:29:00','08:31:00','10:10:00','10:25:00','10:29:00','10:31:00'],
    'B' : ['1','1','1','2','2','2','7','7','7','7'],     
    'C' : ['X','Y','Z','X','Y','Z','A','X','Y','Z'],
    })

df = pd.DataFrame(data=d)

fig,ax = plt.subplots()

x = df['A']
y = df['B']

x_numbers = (pd.to_timedelta(df['A']).dt.total_seconds())

plt.scatter(x_numbers, y)
xaxis = ax.get_xaxis()
ax.set_xticklabels([str(pd.Timedelta(i.get_text()+' seconds')).split()[2] for i in xaxis.get_majorticklabels()], rotation=45)

plt.show()

Any suggestions? Has anyone come across this?

2 Answers2

0

Based on this SO question and answer, one solution is to trigger axis tick positioning with a call to fig.canvas.draw() after the scatter, but before getting the labels:

[...]
plt.scatter(x_numbers, y)
# draw canvas to trigger tick positioning
fig.canvas.draw()
xaxis = ax.get_xaxis()
[...]
Peter Leimbigler
  • 10,775
  • 1
  • 23
  • 37
0
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

d = ({
    'A' : ['08:00:00','08:10:00','08:12:00','08:26:00','08:29:00','08:31:00','10:10:00','10:25:00','10:29:00','10:31:00'],
    'B' : ['1','1','1','2','2','2','7','7','7','7'],     
    'C' : ['X','Y','Z','X','Y','Z','A','X','Y','Z'],
    })

df = pd.DataFrame(data=d)



x = df['A']
y = df['B']
x_numbers = (pd.to_timedelta(df['A']).dt.total_seconds())

fig, axes = plt.subplots(figsize=(10, 4))
axes.scatter(x_numbers, y)
axes.set_xticks(x_numbers)
axes.set_xticklabels([i+' seconds' for i in df['A'].get_values()], rotation=90)
plt.tight_layout()

output:

enter image description here

H.Bukhari
  • 1,951
  • 3
  • 10
  • 15
  • Sorry @H.Bukhari, I need o use something similar to my original code. I'd like the x-ticks to be evenly spread. I don't want them overlapping or tightly bunched. Just an even spread of timestamps –  Jul 04 '18 at 06:26