Как использовать параметр xy в Matplotlib? - PullRequest
0 голосов
/ 21 мая 2019

Рассмотрим следующий блок кода:


%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 в кортеже (x, y), но по какой-то причине это не сработает для меня. Любая помощь будет оценена.

1 Ответ

2 голосов
/ 21 мая 2019

Из-за ваших меток оси 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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...