首页 > 解决方案 > 如何在“Matplotlib”中使用 xy 参数?

问题描述

考虑以下代码块:


%matplotlib inline 
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.style.use('seaborn')
import pandas as pd
import numpy as np 

df_can = pd.read_excel('https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/Data_Files/Canada.xlsx',
                       sheet_name='Canada by Citizenship',
                       skiprows=range(20),
                       skipfooter=2
                      )

# Data Cleaning
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.columns = list(map(str, df_can.columns))

df_can.set_index('Country', inplace=True)

df_can['Total'] = df_can.sum(axis=1)

years = list(map(str, range(1980, 2014)))

# Plotting
df_iceland = df_can.loc['Iceland', years]
df_iceland = pd.DataFrame(df_iceland)

df_iceland.plot(kind='bar', figsize=(10, 6), rot=90) 

plt.xlabel('Year')
plt.ylabel('Number of Immigrants')
plt.title('Icelandic Immigrants to Canada from 1980 to 2013')

# Annotate arrow
plt.annotate('',                      # s: str. will leave it blank for no text
             xy=(32, 70),             # place head of the arrow at point (year 2012 , pop 70)
             xytext=(28, 20),         # place base of the arrow at point (year 2008 , pop 20)
             xycoords='data',         # will use the coordinate system of the object being annotated 
             arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='blue', lw=2)
            )

# Annotate Text
plt.annotate('2008 - 2011 Financial Crisis', # text to display
             xy=(28, 30),                    # start the text at at point (year 2008 , pop 30)
             rotation=72.5,                  # based on trial and error to match the arrow
             va='bottom',                    # want the text to be vertically 'bottom' aligned
             ha='left',                      # want the text to be horizontally 'left' algned.
            )

plt.show()

为什么我需要设置xy = (32, 70)而不是只传入xy = (2012, 70)?我已经看到了一些示例,其中可以直接传入我们想要用作 (x,y) 元组中 x 轴的索引,但由于某种原因,它对我不起作用。任何帮助,将不胜感激。

标签: pythonpandasmatplotlib

解决方案


由于您的 x 轴标签从 1980 年开始,所以这是不可能的,但您可以使用此解决方法。只需从最小索引值中减去您的索引。

# Plotting
df_iceland = df_can.loc['Iceland', years]
df_iceland = pd.DataFrame(df_iceland)

df_iceland.plot(kind='bar', figsize=(10, 6), rot=90) 

plt.xlabel('Year')
plt.ylabel('Number of Immigrants')
plt.title('Icelandic Immigrants to Canada from 1980 to 2013')

min_x =1980

# Annotate arrow
plt.annotate('',                      # s: str. will leave it blank for no text
             xy=(2012-min_x, 70),             # place head of the arrow at point (year 2012 , pop 70)
             xytext=(2008-min_x, 20),         # place base of the arrow at point (year 2008 , pop 20)
             xycoords='data',         # will use the coordinate system of the object being annotated 
             arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='blue', lw=2)
            )



# Annotate Text
plt.annotate('2008 - 2011 Financial Crisis', # text to display
             xy=(2008-min_x, 30),                    # start the text at at point (year 2008 , pop 30)
             rotation=72.5,                  # based on trial and error to match the arrow
             va='bottom',                    # want the text to be vertically 'bottom' aligned
             ha='left',                      # want the text to be horizontally 'left' algned.
            )

plt.show()

推荐阅读