Matplotlib数据框图上缺少X轴标签

时间:2018-11-05 14:38:47

标签: python pandas matplotlib

我遇到一个常见问题,但是其他建议的解决方案似乎不起作用,包括this

当使用的类型是“线”时,X轴上的标签[年份]不显示。我将感谢有人运行该代码并帮助您解决该问题。 预先谢谢你。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('https://raw.githubusercontent.com/princeinzion/NigeriaGDPtoPopulation/master/API_NGA_DS2_en_csv_v2_10185307.csv', skiprows=4)

df = data.loc[[620, 1168], '1999':'2017']

df = df.T

dfp = df.pct_change()

dfp = dfp.reset_index()
dfp.columns = ['Years', 'Population', 'GDP']
dfp

fig = plt.figure(figsize=(20,10))

ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

dfp.plot(kind='line',x='Years',y='GDP', color='red', ax=ax1)
dfp.plot(kind='line',x='Years',y='Population', color='blue', ax=ax2)

plt.show()

以下是我得到的结果。年份不显示在X轴上。 Line Chart

1 个答案:

答案 0 :(得分:2)

将年份转换为这样的日期时间数据类型:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('https://raw.githubusercontent.com/princeinzion/NigeriaGDPtoPopulation/master/API_NGA_DS2_en_csv_v2_10185307.csv', skiprows=4)

df = data.loc[[620, 1168], '1999':'2017']

df = df.T

dfp = df.pct_change()

dfp = dfp.reset_index()
dfp.columns = ['Years', 'Population', 'GDP']
dfp['Years'] = pd.to_datetime(dfp['Years'])
dfp

fig = plt.figure(figsize=(20,10))

ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

dfp.plot(kind='line',x='Years',y='GDP', color='red', ax=ax1)
dfp.plot(kind='line',x='Years',y='Population', color='blue', ax=ax2)

plt.show()

输出:

enter image description here