Luis Henrique
Luis Henrique

Reputation: 771

Reduce X axis in matplotlib

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

Upvotes: 2

Views: 563

Answers (1)

david
david

Reputation: 1501

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

Upvotes: 3

Related Questions