Matplotlib不会在图表上显示日期

时间:2018-03-28 06:05:42

标签: python pandas matplotlib

enter image description here我开始学习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()

然而,当情节显示时,我无法看到日期,我认为它们应该显示,我试图搜索但代码很好,所以它可能是关于可视化工具的东西

有什么想法?提前谢谢。

1 个答案:

答案 0 :(得分:2)

问题似乎是您使用

将数据转换为字符串
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()

输出: enter image description here