Wrong y axis value when two dataset are selected in Matplotlib

Question:

I am trying to plot two datasets (HIBOR and US_yield). I don’t know why the values of HIBOR in the plot are wrong. However, the values are correct when I plot it alone.

import requests
import pandas as pd
import xmltodict
from datetime import datetime
import json
import matplotlib.pyplot as plt

year=2023

us_url=f'https://home.treasury.gov/resource-center/data-chart-center/interest-rates/pages/xml?data=daily_treasury_yield_curve&field_tdr_date_value={year}'
us_data=requests.get(us_url).content

hk_url=f'https://api.hkma.gov.hk/public/market-data-and-statistics/daily-monetary-statistics/daily-figures-interbank-liquidity'
hk_data=requests.get(hk_url).content

# Parase us data
dict_data_us=xmltodict.parse(us_data)
dict_us=dict()
for key in dict_data_us['feed']['entry'][0]['content']['m:properties'].keys():
    dict_us[key.replace('d:','')]=[i['content']['m:properties'][key]['#text'] for i in dict_data_us['feed']['entry']]

df_us=pd.DataFrame(dict_us)
df_us['Date']=[datetime.strptime(i, '%Y-%m-%dT%H:%M:%S') for i in df_us['NEW_DATE']]
df_us.set_index('Date', inplace=True)

# Parase hk data hibor
dict_data_hk=json.loads(hk_data)
dict_hk=dict()
for key in dict_data_hk['result']['records'][0].keys():
    dict_hk[key]=[i[key] for i in dict_data_hk['result']['records']]

df_hk=pd.DataFrame(dict_hk)
df_hk['Date']=[datetime.strptime(i, '%Y-%m-%d') for i in df_hk['end_of_date']]
df_hk.set_index('Date', inplace=True)

df_hk.sort_index(inplace=True)

plt.plot(df_hk['hibor_fixing_1m'][-40:], label='HIBOR_1M')
plt.plot(df_us['BC_1MONTH'][-40:], label='US_Yield_1M')
plt.legend()
plt.show()

enter image description here

enter image description here

Asked By: mogcai

||

Answers:

The reason is that the y-axis fields are read as string in your plot. You need to add astype(float) to them as below…

plt.plot(df_us['BC_1MONTH'][-40:].astype(float), label='US_Yield_1M')
plt.plot(df_hk['hibor_fixing_1m'][-40:].astype(float), label='HIBOR_1M')

This will give you the below plot. Hope this is what you are looking for

enter image description here

Answered By: Redox
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.