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

2024-09-26 18:15:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个金融市场收益的自相关图,并使用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()

下面是相应的自相关图本身:

enter image description here

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


Tags: 方法importnoneplot颜色figpltred
1条回答
网友
1楼 · 发布于 2024-09-26 18:15:28

我怀疑他们(意外地)硬编码了置信区间的颜色,否决了用户所做的任何更改(例如,该区域的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()

enter image description here

更新
考虑到关键字、字典和回顾性更改的混乱方法,我认为在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()

相关问题 更多 >

    热门问题