Loop to graph into a Dict Python MATPLOTLIB

六眼飞鱼酱① 提交于 2021-01-29 05:23:36

问题


What i'm trying to do here is to make a loop to create multiple graphs of dicts.

I looped to execute univariate rolling window regressions and I stored the COEFS and the R_SQ of each variable in a DICT.

the DICT itsel got 23 sub DICT each containing my a series of coefficients and rsquareds from 2008 to 2020 (4580 obs.)

It goes like this (for visualisation):

data1
   BE10USD
     params - const & coef 
     r_sq
   BE30CAD
     params - const & coef 
     r_sq
   SWAP1YUSD
     params - const & coef 
     r_sq

And on, my dict is composed of 23 "sub dicts" like this.

SO, what i'd like to do, is loop to create graph of all these subdiscts. In detail, I'd like to graph the evolution of the r_sq and the coef in time.

Here was my code for a simple graph (of one variable), I really liked the results of this one:

#Plot
fig1 = rres.plot_recursive_coefficient(variables=['BE10USD'], figsize=(14,6))

#Label names
plt.xlabel('Date')
plt.ylabel('R.squared & Coefficient')

#Add r2
r_sq.plot()

#Add legend
import matplotlib.patches as mpatches
orange_patch = mpatches.Patch(color='orange', label='r2')
blue_patch = mpatches.Patch(color='blue', label='Coefficient')
plt.legend(handles=[orange_patch,blue_patch])

Would there be a way to loop this graph into all the dict, giving the dict Key the title of the graph?

I'm new to python so any help you can provide would be super helpfull. Thank you!


回答1:


I don't fully understand your workspace and variables from your provided scripts, but in principle it's simple to loop through any iterable in python and use matplotlib commands to call plots within the loop. Here is an example:

  • color_list is a list of hex strings, indicating colorper plot
  • mydict is your parent dictionary (or any subdictionary, access accordingly)
  • I assume your data is in mydict[key]
# plotting recursively in one plot
fig, ax = plt.subplots(1,1,figsize=(12,8))

for key, color in zip(mydict.keys(), color_list):
    ax.plot(mydict[key], label=key, ls='--', color=color)
# plotting recursively in multiple subplots (single column)
fig, ax = plt.subplots(5,1,figsize=(14,12))

for i,key,color in enumerate(zip(mydict.keys(), color_list)):
    ax[i,1].plot(mydict[key], label=key, ls='--', color=color)

Treat individual subplot settings within your loop. You can then finalize parent plot properties (such as the legend or axes limits) outside the loop. Of course, things get more tricky if you need to divide subplots across multiple axes (i.e. in a grid) and you may then want to create a function using the modulo % to get from a single index i to a grid nrow, ncol.



来源:https://stackoverflow.com/questions/65844889/loop-to-graph-into-a-dict-python-matplotlib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!