1

In R, we could plot each graph independently and then arrange all or some of the graphs easily by packages like gridExtra. For example,

p1 <- ggplot(aes(x1,y1), data=df) + geom_point()
p2 <- ggplot(aes(x2,y2), data=df) + geom_point()
p3 <- ggplot(aes(x3,y3), data=df) + geom_point()
p4 <- ggplot(aes(x4,y4), data=df) + geom_point()

I plot 4 graphs, and now I just want put 2 of them side by side to do some analysis, so I could

grid.arrange(p1, p2, ncol=1)
grid.arrange(p1, p3, ncol=1)
...

I find this is quite convenient for us to arbitrarily to combine and arrange independent graphs. However, can we do the same thing in Python with matplotlib? The big problem here is that I do not know how many graphs are there before hand and either how I want to combine and arrange them.

Alcott
  • 16,879
  • 27
  • 109
  • 172
  • See http://matplotlib.org/faq/usage_faq.html#coding-styles – tacaswell Oct 03 '14 at 04:12
  • and http://stackoverflow.com/questions/18284296/matplotlib-using-a-figure-object-to-initialize-a-plot/18302072#18302072 – tacaswell Oct 03 '14 at 04:13
  • and http://stackoverflow.com/questions/22606665/how-to-plot-2-subplots-from-different-functions-in-the-same-windowfigure/22612754#22612754 – tacaswell Oct 03 '14 at 04:14
  • @tcaswell, if I understand correctly, you mean create multiple `axes`, and then use these axes to draw stuff I want, right? Well if so, that means I should know how many axes I need and how they are arranged in one figure, but this is not the case I described in the post. – Alcott Oct 03 '14 at 05:00
  • also http://stackoverflow.com/questions/16750333/how-do-i-include-a-matplotlib-figure-object-as-subplot/16754215#16754215 – tacaswell Oct 03 '14 at 12:03
  • and https://github.com/yhat/ggplot is a project that aims to build an R-like interface on top of mpl – tacaswell Oct 03 '14 at 12:16

1 Answers1

-1

Maybe gridspec would work for you? I use it to display/generate differents reports and summaries

http://matplotlib.org/users/gridspec.html

If not, maybe a simple wrapper for arbitrary comparisons?

import matplotlib.pyplot as plt

def compare(data, fig, rows, cols ):
    for i in range (0,len(data)):
        plt.figure(fig)
        plt.subplot(rows, cols, i+1)
        plt.plot(data[i])
    return

d1 = [1, 2, 3, 4]
d2 = [4, 3, 2, 1]
d3 = [4, 3, 3, 1]
d4 = [3, 4, 1, 2]
data = [d2,d1,d4]

# compare 4 horizontally
compare([d1, d2, d3, d4], fig=1, rows=1, cols=4)
# compare 4 vertically
compare([d1, d2, d3, d4], fig=2, rows=4, cols=1)
# compare 2 vertically
compare([d2, d3], fig=3, rows=2, cols=1)
# compare 3 horizontally
compare([d1, d2, d4], fig=4, rows=1, cols=3)
# compare 3 vertically
compare(data, fig=5, rows=3, cols=1)
plt.tight_layout()
plt.show()