繁体   English   中英

Matplotlib x轴和副y轴定制问题

[英]Matplotlib x-axis and secondary y-axis customization questions

数据 - 我们导入 10 年和 30 年期国债的历史收益率并计算两者之间的利差(差异) (这段代码很好;随意跳过):

#Import statements 
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

#Constants 
start_date = "2018-01-01"
end_date = "2023-01-01"

#Pull in data
tenYear_master = yf.download('^TNX', start_date, end_date)
thirtyYear_master = yf.download('^TYX', start_date, end_date)

#Trim DataFrames to only include 'Adj Close columns'
tenYear = tenYear_master['Adj Close'].to_frame()
thirtyYear = thirtyYear_master['Adj Close'].to_frame()

#Rename columns
tenYear.rename(columns = {'Adj Close' : 'Adj Close - Ten Year'}, inplace= True)
thirtyYear.rename(columns = {'Adj Close' : 'Adj Close - Thirty Year'}, inplace= True)

#Join DataFrames
data = tenYear.join(thirtyYear)

#Add column for difference (spread)
data['Spread'] = data['Adj Close - Thirty Year'] - data['Adj Close - Ten Year']

data

在此处输入图像描述

这个版块也不错。

'''Plot data'''
#Delete top, left, and right borders from figure 
plt.rcParams['axes.spines.top'] = False
plt.rcParams['axes.spines.left'] = False
plt.rcParams['axes.spines.right'] = False
fig, ax = plt.subplots(figsize = (15,10))
data.plot(ax = ax, secondary_y = ['Spread'], ylabel = 'Yield', legend = False);

'''Change left y-axis tick labels to percentage'''
left_yticks = ax.get_yticks().tolist()
ax.yaxis.set_major_locator(mticker.FixedLocator(left_yticks))
ax.set_yticklabels((("%.1f" % tick) + '%') for tick in left_yticks);

#Add legend 
fig.legend(loc="upper center", ncol = 3, frameon = False)
fig.tight_layout()
plt.show()

在此处输入图像描述

我对要自定义的图形的两个功能有疑问:

  1. x 轴目前有一个刻度和刻度 label 代表每年。 我怎样才能改变这个,以便每 3 个月在 MMM-YY 表格中有一个勾号和勾号 label? (见下图)

在此处输入图像描述

  1. 利差计算为三十年收益率 - 十年收益率。 假设我想更改 RIGHT y 轴刻度标签,以便翻转它们的符号,但我想单独保留原始数据和曲线(为了争论;请耐心等待,这背后有逻辑)。 换句话说,右侧 y 轴刻度标签当前为 go,从底部的 -0.2 到顶部的 0.8。 我怎样才能改变它们,使它们 go 从底部的 0.2 到顶部的 -0.8,而不改变任何数据或曲线? 这纯粹是对右侧 y 轴刻度标签的外观更改。

我尝试执行以下操作:

'''Change right y-axis tick labels'''
right_yticks = (ax.right_ax).get_yticks().tolist()
#Loop through and multiply each right y-axis tick label by -1
for index, value in enumerate(right_yticks):
  right_yticks[index] = value*(-1)
(ax.right_ax).yaxis.set_major_locator(mticker.FixedLocator(right_yticks))
(ax.right_ax).set_yticklabels(right_yticks)

但我得到了这个:

在此处输入图像描述

请注意右侧的 y 轴是如何不完整的。

我将不胜感激任何帮助。 谢谢!

让我们创建一些数据:

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

days = np.array(["2022-01-01", "2022-07-01", "2023-02-15", "2023-11-15", "2024-03-03"],
                 dtype = "datetime64")
val = np.array([20, 20, -10, -10, 10])

对于 x 轴中的日期,我们导入 matplotlib.dates,它提供月份定位器和日期格式器。 定位器每 3 个月设置一次刻度,格式化器设置标签的显示方式 (month-00)。

对于 y 轴数据,您需要更改数据的符号(因此 ax2.plot() 中的负号,但您希望曲线在相同的 position 中,因此之后您需要反转轴。因此,两个图中的曲线相同,但 y 轴值具有不同的符号和方向。

fig, (ax1, ax2) = plt.subplots(figsize = (10,5), nrows = 2)

ax1.plot(days, val, marker = "x")
# set the locator to Jan, Apr, Jul, Oct
ax1.xaxis.set_major_locator(mdates.MonthLocator( bymonth = (1, 4, 7, 10) ))
# set the formater for month-year, with lower y to show only two digits
ax1.xaxis.set_major_formatter(mdates.DateFormatter("%b-%y"))

# change the sign of the y data plotted
ax2.plot(days, -val, marker = "x")
#invert the y axis
ax2.invert_yaxis()
# set the locator to Jan, Apr, Jul, Oct
ax2.xaxis.set_major_locator(mdates.MonthLocator( bymonth = (1, 4, 7, 10) ))
# set the formater for month-year, with lower y to show only two digits
ax2.xaxis.set_major_formatter(mdates.DateFormatter("%b-%y"))

plt.show()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM