I'm plotting a visualization with two y axes each representing a dataframe column. I used one of the dataframe's (both dataframes have the same index) index as the x-axis, however the xticks labels are not showing correctly. I should have years from 2000 to 2018
I used the following code to create the plot:
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(df1.index, df1, 'g-')
ax2.plot(df1.index, df2, 'b-')
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')
plt.show()
the index of df1 is as follows:
Index(['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008',
'2009', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016',
'2017', '2018'],
dtype='object')
Here's a small snippet of the two dfs:
df1.head()
gdp
2000 1.912873
2001 7.319967
2002 3.121450
2003 5.961162
2004 4.797018
df2.head()
lifeex
2000 68.684
2001 69.193
2002 69.769
2003 70.399
2004 71.067
I tried different solutions including the one in Set Xticks frequency to dataframe index but none has succeeded to get all years showing. I really appreciate if someone can help. thanks in advance
When I try ax1.set_xticks(df1.index)
I get the following error: '<' not supported between instances of 'numpy.ndarray' and 'str'