python - Matplotlib 不在图表上显示日期

标签 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()

但是,当绘图显示时,我看不到日期,我认为它们应该显示,我试图搜索,但代码很好,所以这可能与可视化工具有关。

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

最佳答案

问题似乎是您将数据转换为字符串

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

关于python - Matplotlib 不在图表上显示日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527229/

相关文章:

PYTHON:如何在 Python 中使用 raw_input 将 .txt 文件作为用户的输入,然后逐行读取该文件?

python - 在TensorFlow中显示图形图像?

python - 当系列包含集合时,为什么我的 pandas rolling().apply() 不起作用?

python - 在 JupyterNotebook 图中并排显示 Pandas DataFrame 和 Matplotlib

python - matplotlib 中的堆积面积图和日期

python - ipython笔记本中的绘图宽度设置

python - Django Sass 压缩器 django_libsass.SassCompiler : command not found

python - 如何使用 df.replace(key :value) inside for loop in python

python - 如何在这个for循环中使用subplot在单图中显示多张图片?

python - 在子进程中使用多处理