如何在 statsmodel 的 plot_acf 函数中更改颜色?

How to change color in statsmodel's plot_acf function?

我想创建金融市场的自相关图 returns 并为此使用 statsmodel 的 plot_acf() 函数。但是,我试图改变所有绘图元素的颜色,但我的方法只修改了标记的颜色。但是,条形图和置信区间都没有收到 color="red" 参数。我正在使用 Python (3.8.3) 和 Statsmodels (0.12.1)。

下面显示了我当前的自相关图方法的简单代码片段:

# import required package
import pandas as pd
from statsmodels.graphics.tsaplots import plot_acf
# initialize acplot
fig, ax = plt.subplots(nrows=1, ncols=1, facecolor="#F0F0F0")
# autocorrelation subplots
plot_acf(MSCIFI_ret["S&P500"], lags=10, alpha=0.05, zero=False, title=None, ax=ax, color="red")
ax.legend(["S&P500"], loc="upper right", fontsize="x-small", framealpha=1, edgecolor="black", shadow=None)
ax.grid(which="major", color="grey", linestyle="--", linewidth=0.5)
ax.set_xticks(np.arange(1, 11, step=1))
# save acplot
fig.savefig(fname=(plotpath + "test.png"))
plt.clf()
plt.close()

这是相应的自相关图本身:

有谁知道如何处理这个问题?任何想法将不胜感激。

我怀疑他们(不小心?)对置信区间的颜色进行了硬编码,否决了用户所做的任何更改(例如,可以修改此区域的 edgecolor)。我在 the source code 中没有看到更改 CI 多边形颜色的方法。 rcParams["patch.facecolor"] = "red" 应该改变颜色,唉,它没有。但是我们可以追溯改变生成的多边形的颜色:

import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from matplotlib.collections import PolyCollection

#sample data from their website
dta = sm.datasets.sunspots.load_pandas().data
dta.index = pd.Index(sm.tsa.datetools.dates_from_range('1700', '2008'))
del dta["YEAR"]

curr_fig, curr_ax = plt.subplots(figsize=(10, 8))

my_color="red"
#change the color of the vlines
sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40, ax=curr_ax, color=my_color, vlines_kwargs={"colors": my_color})
#get polygon patch collections and change their color
for item in curr_ax.collections:
    if type(item)==PolyCollection:
        item.set_facecolor(my_color)

plt.show()

更新
鉴于关键字、kwarg 词典和追溯更改的混乱方法,我认为在 statsmodels 绘制图表后更改所有颜色时代码可能更具可读性:

...
from matplotlib.collections import PolyCollection, LineCollection
...
curr_fig, curr_ax = plt.subplots(figsize=(10, 8))

sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40, ax=curr_ax)

my_color="red"

for item in curr_ax.collections:
    #change the color of the CI 
    if type(item)==PolyCollection:
        item.set_facecolor(my_color)
    #change the color of the vertical lines
    if type(item)==LineCollection:
        item.set_color(my_color)    

#change the color of the markers/horizontal line
for item in curr_ax.lines:
    item.set_color(my_color)

plt.show()