我开始学习 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()
关于python - Matplotlib 不在图表上显示日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527229/