3

In short, I want to write a function that will output a scatter matrix and boxplot at one time in python. I figured I would do this by created a figure with a 2x1 plotting array. However when I run the code using a Jupyter notebook:

def boxplotscatter(data):
    f, ax = plt.subplots(2, 1, figsize = (12,6))
    ax[0] = scatter_matrix(data, alpha = 0.2, figsize = (6,6), diagonal = 'kde')
    ax[1] = data.boxplot()

I get, using data called pdf:

enter image description here

That isn't exactly what I expected -- I wanted to output the scatter matrix and below it the boxplot, not two empty grids and a boxplot embedded in a scatter matrix.

Thoughts on fixing this code?

Community
  • 1
  • 1
zthomas.nc
  • 3,689
  • 8
  • 35
  • 49

2 Answers2

1

I think you just need to pass the axis as an argument of your plotting function.

f, ax = plt.subplots(2, 1, figsize = (12,6))
def boxplotscatter(data, ax):
    ax[0] = scatter_matrix(data, alpha = 0.2, figsize = (6,6), diagonal = 'kde')
    ax[1] = data.boxplot()
josecoto
  • 732
  • 1
  • 7
  • 15
  • This removes the extraneous empty grids but doesn't "pop out" the boxplot from being embedded within the scatter matrix. – zthomas.nc Sep 28 '16 at 14:31
  • Hey, I think this behaviour is due because pandas plotting is already calling a figure from within its function. That means that it will be displayed whenever is called. Anyway, given that the function returns it axes, I was checking if there was a way to decouple those axis from the figure itself and passing it to a layout that you want (so you can add different plots afterwards). However, reading this, it turns out this is not an option [link](http://stackoverflow.com/questions/6309472/matplotlib-can-i-create-axessubplot-objects-then-add-them-to-a-figure-instance). – josecoto Sep 30 '16 at 10:25
  • ^ Feel free to spin this off into its own answer, I think this more or less answers it for me. – zthomas.nc Oct 03 '16 at 15:45
0

The issue here is that you are not actually plotting on the created axes , you are just replacing the content of your list ax. I'm not very familiar with the object oriented interface for matplotlib but the right syntax would look more like ax[i,j].plot() rather than ax[i] = plot(). Now the only real solution I can provide is using functional interface, like that :

def boxplotscatter(data):
    f, ax = plt.subplots(2, 1, figsize = (12,6))
    plt.subplot(211)
    scatter_matrix(data, alpha = 0.2, figsize = (6,6), diagonal = 'kde')  
    plt.subplot(212)
    data.boxplot()
jadsq
  • 3,033
  • 3
  • 20
  • 32