gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:36 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com