Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
55 views
in Technique[技术] by (71.8m points)

python - Using dataframe index containing the year as x axis

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

The plot looks like: df index

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'

question from:https://stackoverflow.com/questions/65644735/using-dataframe-index-containing-the-year-as-x-axis

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I couldn't duplicate your issue (mpl.version = 3.2.2):

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df1 = pd.DataFrame({'col1':np.random.randint(1,7 , 19)}, 
                   index=[str(i) for i in range(2000,2019)])

print(df1.index)

df2 = pd.Series(np.linspace(69,78, 19))

fig, ax1 = plt.subplots(figsize=(15,8))
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()

Output:

Index(['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008',
       '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017',
       '2018'],
      dtype='object')

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...