Reputation: 11002
I have a project where I draw and save figures with matplotlib. Since the project itself worked perfectly I recently started refactoring but there is one problem which I have not found a good solution for yet. To split implementation and logging I wrote a logging class which passes the data to a plotting class and there I got an issue: before runtime I do not know how many subplots will exist in one logging plot/figure.
So, before refactoring I had a lot of different plotting functions and many if statements. Now I want to pass all that stuff to my plotting class...but I do not have a good idea at the moment how the plotting class should handle this data.
Beforehand I had something like this (here: for 4 subplots):
f, axarr = plt.subplots(2, 2)
axarr[0, 0].set_title("original image")
axarr[0, 0].imshow(oimg, interpolation="none", cmap="gray")
axarr[0, 1].set_title("cost data")
axarr[0, 1].plot(cost_data, ...)
(...)
Of course I could create like 6 different methods like this in my plotting class for 1, 2, 3, ... subplots but then I have the repetition there again.
Can I somehow create a buffer and dynamically add a subplot in a loop or something like that?
Any other ideas?
Upvotes: 0
Views: 1028
Reputation: 87536
def plotA(ax, data):
pass
def plotB(ax, data):
pass
def dispatcher(data, list_of_plot_types):
function_map = {'A': plotA, 'B': plotB}
fig, list_of_axes = plt.subplots(1, len(list_of_plot_types))
for ax, plot_type in zip(list_of_axes, list_of_plot_types):
function_map[plot_type](ax, data)
Upvotes: 2