1

I have two data sets and trying to show to data sets on the same graph for comparison. when plotting bar graphs on the same fig. I am seeing that 2 values are overshooting the x-axis. when I try individually, each graph looks good.2019-5-20,2019-5-28 data from second set comes at the end, not in the order.

My first data set looks like:

drray1 ['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]

and my second data set looks like:

drray2 ['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]

when I try to plot bar graphs:

p1=plt.bar(darray1,countarray1,color="blue",edgecolor='white', 
width=barWidth,label="First Load")

p1=plt.bar(darray2,countarray2,color="Green", width=barWidth,label="Second Load")
plt.show()
Valentino
  • 7,291
  • 6
  • 18
  • 34
VKS
  • 55
  • 1
  • 5

1 Answers1

0

Currently you are plotting strings so the order of dates is not recognized. You need to convert the strings dates into datetime objects using the method as shown here

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

fig, ax = plt.subplots()

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)
plt.show()

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • How to show all date values in x-axis. in the solution you solved, the graph is not showing all values on x-axes. I tried multiple ways. thanks – VKS Jun 17 '19 at 03:01