2

How reduce X axis in matplotlib when values is extensive ?

I would like to show, example:

2020-04-04 9:00:01, 2020-04-04 9:20:01, 2020-04-04 9:40:01...

Thus, the data would not group.

Example script:

try:
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib import rc

except ImportError as e:
    print("[ALERT] Error import caused by: {}".format(e))
    sys.exit()

valueA = [8,9,10,9,8,8,9,10,9,8,8,9,10,9,8,8,9,10,9,8,8,9,10,9,8]
valueB = [8,9,10,9,8,8,9,10,9,8,8,9,10,9,8,8,9,10,9,8,8,9,10,9,8]

time = pd.date_range(start = '2020-04-04 9:00:01', periods = 50, freq='T')
x_plot = range(len(time))

plt.plot(np.arange(0, len(valueA)), valueA, 'g', label="valueA")
plt.plot(np.arange(len(valueA), len(valueA) + len(valueB)), valueB, 'r', label="valueB")
plt.xticks(rotation=90)
plt.xticks(x_plot, time)
plt.ylabel('Value')
plt.xlabel('Time Step')
plt.legend()
plt.show()

Result:

enter image description here

1 Answer 1

3

Using matplotlib.dates, I change X values with date2num, I then format xaxis with DateFormater and MinuteLocator with byminute option. I finally call autofmt_xdate()

try:
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib import rc
    import matplotlib.dates as mdates

except ImportError as e:
    print("[ALERT] Error import caused by: {}".format(e))
    sys.exit()

valueA = [8,9,10,9,8,8,9,10,9,8,8,9,10,9,8,8,9,10,9,8,8,9,10,9,8]
valueB = [8,9,10,9,8,8,9,10,9,8,8,9,10,9,8,8,9,10,9,8,8,9,10,9,8]

time = pd.date_range(start = '2020-04-04 9:00:01', periods = 50, freq='T')
X = mdates.date2num(time)

plt.plot(X[:len(valueA)], valueA, 'g', label="valueA")
plt.plot(X[len(valueA):], valueB, 'r', label="valueB")

plt.ylabel('Value')
plt.xlabel('Time Step')
plt.legend()

ax = plt.gca()
fmt = mdates.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(fmt)
m = mdates.MinuteLocator(byminute=range(0, 50, 20))
ax.xaxis.set_major_locator(m)
ax.xaxis_date()

fig = plt.gcf()
fig.autofmt_xdate()

plt.show()

enter image description here

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

1 Comment

Perfect, this was exactly the doubt, thank you for your help!

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.