Python Matplotlib不在图表上显示日期

Python Matplotlib不在图表上显示日期,python,pandas,matplotlib,Python,Pandas,Matplotlib,我开始学习Matplotlib,我安装了pip,一切运行正常,我能够用以下代码创建图表: import matplotlib.pyplot as plt import matplotlib as mpl import pandas as pd import numpy as np df_can = pd.read_excel( 'Canada.xlsx', sheet_name='Canada by Citizenship', skiprows=range(20

我开始学习Matplotlib,我安装了pip,一切运行正常,我能够用以下代码创建图表:

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

df_can = pd.read_excel(    
    'Canada.xlsx',
    sheet_name='Canada by Citizenship',
    skiprows=range(20),
    skip_footer=2)

def data_format(df_can):
    df_can.index.values
    df_can.index.tolist()
    df_can.drop(['AREA','REG','DEV','Type','Coverage'], axis=1, inplace=True)
    df_can.rename(columns={'OdName':'Country', 'AreaName':'Continent', 'RegName':'Region'}, inplace=True)
    df_can['Total'] = df_can.sum(axis=1)
    df_can.set_index('Country', inplace=True)

data_format(df_can)

df_can.columns = list(map(str, df_can.columns))
years = list(map(str, range(1980, 2014)))


df_can.sort_values(by='Total', ascending=False, axis=0, inplace=True)


df_top5 = df_can.head(5)

df_top5 = df_top5[years].transpose()

df_top5.plot(kind='area', figsize=(14, 8)) 

plt.title('Immigration Trend of Top 5 Countries')
plt.ylabel('Number of Immigrants')
plt.xlabel('Years')

plt.show()
然而,当绘图显示时,我看不到日期,我认为它们应该显示出来,我试图搜索,但代码很好,因此可能与可视化工具有关


有什么想法吗?提前感谢。

问题似乎是您使用

df_can.columns = list(map(str, df_can.columns))
years = list(map(str, range(1980, 2014)))
使你的情节成为分类情节。有很多方法可以在之后标记绘图,但为什么不简单地保留数字数据呢

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

df_can = pd.read_excel(    
    'Canada.xlsx',
    sheet_name='Canada by Citizenship',
    skiprows=range(20),
    skip_footer=2)

def data_format(df_can):
    df_can.index.values
    df_can.index.tolist()
    df_can.drop(['AREA','REG','DEV','Type','Coverage'], axis=1, inplace=True)
    df_can.rename(columns={'OdName':'Country', 'AreaName':'Continent', 'RegName':'Region'}, inplace=True)
    df_can['Total'] = df_can.sum(axis=1)
    df_can.set_index('Country', inplace=True)

data_format(df_can)

df_can.sort_values(by='Total', ascending=False, axis=0, inplace=True)
#keep only columns with yearly data
df_top5 = df_can.head(5).drop(["Continent", "Region", "DevName", "Total"], axis = 1).transpose()

df_top5.plot(kind='area', figsize=(14, 8)) 

plt.title('Immigration Trend of Top 5 Countries')
plt.ylabel('Number of Immigrants')
plt.xlabel('Years')

plt.show()
输出:

加拿大.xlsx是否在某处公开?@DynoFu是的,我已将数据下载到我的电脑上。@MrT您可以从以下链接获取日期:,我添加了一个图像,显示我的意思,我看不到日期。谢谢你的建议,你是对的。它成功了,下次将把数据转换成str。