VKS
VKS

Reputation: 55

How to show all date values on the x-axis?

I have the following dates on the x-axis and the graph is not showing all values. What setting do I need to show all x-values?

drray2 ['2019-04-23', '2019-04-25', '2019-04-29', '2019-04-30', '2019-05-01', '2019-05-02', '2019-05-06', '2019-05-13', '2019-05-15', '2019-05-16', '2019-05-20', '2019-05-23', '2019-05-24', '2019-05-28', '2019-06-11', '2019-06-12', '2019-06-14']
countarray2 [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 3, 1]

p1=plt.bar(converted_dates_2,countarray2,color="Green", width=barWidth,label="second load")
plt.show()

Upvotes: 4

Views: 6619

Answers (2)

Sheldore
Sheldore

Reputation: 39052

You can use a frequency of 1 for the x-axis as

ax.xaxis.set_major_locator(dates.DayLocator(interval=1))

Complete answer using the code you gave previously

import matplotlib.pyplot as plt
from matplotlib import dates
import datetime

fig, ax = plt.subplots(figsize=(8, 6))

darray1 = ['2019-05-21', '2019-05-22', '2019-05-23', '2019-05-24', '2019-05-27', '2019-05-29', 
          '2019-05-31', '2019-06-01', '2019-06-03', '2019-06-04', '2019-06-07', '2019-06-10', 
          '2019-06-11', '2019-06-12', '2019-06-13', '2019-06-14'] 
countarray1 = [1, 1, 2, 1, 1, 1, 2, 1, 2, 4, 3, 9, 4, 2, 7, 3]

darray2 = ['2019-05-20', '2019-05-23', '2019-05-24', '2019-05-28', '2019-06-11', '2019-06-12', '2019-06-14'] 
countarray2 = [1, 2, 1, 1, 1, 3, 1]

converted_dates_1 = list(map(datetime.datetime.strptime, darray1, len(darray1)*['%Y-%m-%d']))
converted_dates_2 = list(map(datetime.datetime.strptime, darray2, len(darray2)*['%Y-%m-%d']))
formatter = dates.DateFormatter('%Y-%m-%d')

plt.bar(converted_dates_1,countarray1,color="blue",edgecolor='white', width=0.5,label="First Load")
plt.bar(converted_dates_2,countarray2,color="Green", width=0.5,label="Second Load") 

ax.xaxis.set_major_formatter(formatter)
plt.gcf().autofmt_xdate(rotation=90)
ax.xaxis.set_major_locator(dates.DayLocator(interval=1))

plt.show()

enter image description here

Upvotes: 3

arajshree
arajshree

Reputation: 624

Not eaxcly sure why it not showing for you, I ran it locally with xticks property : Code:

x = ['2019-04-23', '2019-04-25', '2019-04-29', '2019-04-30', '2019-05-01', '2019-05-02', '2019-05-06', '2019-05-13', '2019-05-15', '2019-05-16', '2019-05-20', '2019-05-23', '2019-05-24', '2019-05-28', '2019-06-11', '2019-06-12', '2019-06-14']
y = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 3, 1]
plt.bar(x,y,color="Green")
plt.xticks(rotation=90)
plt.show()

And the graph is :

Final Plot

Upvotes: 1

Related Questions