a
and b
are datetime indexes for the A Values
and B Values
, respectively . The size of the A Values
is greater than of the B Values
I want to reproduce a code where I place them on the same graph. How would I be able to write a code where it graphs 2 numpy array with different lengths on the same graph?
import pandas as pd
import numpy as np
import datetime
a = np.array(['2017-09-15 07:11:00', '2017-09-15 12:11:00', '2017-12-22 06:35:00'], dtype='datetime64[ns]')
b = np.array(['2017-09-10 02:25:00', '2017-12-11 03:11:00'], dtype='datetime64[ns]')
graph= pd.DataFrame({
'A Values': np.array([11,-3,4]),
'B Values': np.array([2,4])
}, index= [a,b]).plot.line()
Error Code:
ValueError: all arrays must be same length
CodePudding user response:
You can pad the arrays to same size with filling small array to zero or none : use this snippet to make it :
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import datetime
a = np.array(['2017-09-15 07:11:00', '2017-09-15 12:11:00', '2017-12-22 06:35:00'], dtype='datetime64[ns]')
b = np.array(['2017-09-10 02:25:00', '2017-12-11 03:11:00'], dtype='datetime64[ns]')
s1=[11,-3,4]
s2=[2,4]
m = max(len(s1),len(s2))
a1=[None] * m
a2=[None] * m
ax1=[None] * m
ax2=[None] * m
for i in range(len(s1)):
a1[i] = s1[i]
ax1[i]=a[i]
for i in range(len(s2)):
a2[i] = s2[i]
ax2[i]=b[i]
graph= pd.DataFrame({
'A Values': np.array(a1),
'B Values': np.array(a2)
}, index= [ax1,ax2]).plot.line()
plt.xticks(rotation=0)
plt.tick_params(axis='both', which='major', labelsize=5)
#labelsize=5 instead of labelsize=10
plt.show()
Output:
I hope you find it useful
CodePudding user response:
Just catch the axis object generated by matplotlib for the first plot and use it to plot the second series:
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
a = np.array(['2017-09-15 07:11:00', '2017-09-15 12:11:00', '2017-12-22 06:35:00'], dtype='datetime64[ns]')
b = np.array(['2017-09-10 02:25:00', '2017-12-11 03:11:00'], dtype='datetime64[ns]')
ax1 = pd.DataFrame({'A Values': np.array([11,-3,4])}, index= a).plot.line()
pd.DataFrame({'B Values': np.array([2,4])}, index= b).plot.line(ax=ax1)
plt.show()
In case you were wondering what matplotlib has to do with your question - unless specified otherwise, pandas gives the data to matplotlib to generate plots.