1

say I was testing a range of parameters of a clustering algorithm and I wanted to write python code that would plot all the results of the algorithm in subplots 2 to a row

is there a way to do this without pre-calculating how many total plots you would need?

something like:

for c in range(3,10):
    k = KMeans(n_clusters=c)
    plt.subplots(_, 2, _)
    plt.scatter(data=data, x='x', y='y', c=k.fit_predict(data))

... and then it would just plot 'data' with 'c' clusters 2 plots per row until it ran out of stuff to plot.

thanks!

steadynappin
  • 409
  • 3
  • 14
  • What's the problem of creating the data to plot first and then loop over the data? – ImportanceOfBeingErnest Jun 18 '18 at 10:46
  • iuno man when i get in a car i dont have to tell it exactly where im going every time i start driving... this just seems like something that should be possible – steadynappin Jun 18 '18 at 14:12
  • Sure, if you create a figure, you don't need to know how many subplots it'll get. But if you create a subplot, you need to know where it should be placed. You can of course move all previous subplots in a loop step once a new subplot(-row) needs to be created, but that seems cumbersome compared to the straight forward solution of finding out the positions beforehands. So in total it just feels strange to get into the car without knowing where to go. – ImportanceOfBeingErnest Jun 18 '18 at 14:22
  • it doesnt sound like u have an answer to the question so.......... – steadynappin Jun 18 '18 at 14:50
  • 1
    I can show you how to move once created subplots to new positions and thus answer the question. My comments are meant to convince you that this is a suboptimal solution and that it would be better to find out how many subplots you will need prior to creating them. – ImportanceOfBeingErnest Jun 18 '18 at 16:43
  • 1
    But what you ask is not clear either. If you use a `for` loop you know exactly how many plots you will create - in the case of the example it will be 7. So you can simply put in `plt.subplot(7,2,(c-2)*2)` (mind `subplot` without `s`). – ImportanceOfBeingErnest Jun 18 '18 at 21:53

1 Answers1

0

This answer from the question Dynamically add/create subplots in matplotlib explains a way to do it: https://stackoverflow.com/a/29962074/3827277

verbatim copy & paste:

import matplotlib.pyplot as plt

# Start with one
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])

# Now later you get a new subplot; change the geometry of the existing
n = len(fig.axes)
for i in range(n):
    fig.axes[i].change_geometry(n+1, 1, i+1)

# Add the new
ax = fig.add_subplot(n+1, 1, n+1)
ax.plot([4,5,6])

plt.show() 
philn
  • 654
  • 6
  • 17