3

In a jupyter notebook, I have a function which prepares the input features and targets matrices for a tensorflow model.

Inside this function, I would like to display a correlation matrix with a background gradient to better see the strongly correlated features.

This answer shows how to do that exactly how I want to do it. The problem is that from the inside of a function I cannot get any output, i.e. this:

def display_corr_matrix_custom():
    rs = np.random.RandomState(0)
    df = pd.DataFrame(rs.rand(10, 10))
    corr = df.corr()
    corr.style.background_gradient(cmap='coolwarm')

display_corr_matrix_custom()

clearly does not show anything. Normally, I use IPython's display.display() function. In this case, however, I cannot use it since I want to retain my custom background.

Is there another way to display this matrix (if possible, without matplotlib) without returning it?


EDIT: Inside my real function, I also display other stuff (as data description) and I would like to display the correlation matrix at a precise location. Furthermore, my function returns many dataframes, so returning the matrix as proposed by @brentertainer does not directly display the matrix.

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
David
  • 513
  • 7
  • 26

1 Answers1

2

You mostly have it. Two changes:

  • Get the Styler object based from corr.
  • Display the styler in the function using IPython's display.display()
def display_corr_matrix_custom():
    rs = np.random.RandomState(0)
    df = pd.DataFrame(rs.rand(10, 10))
    corr = df.corr()  # corr is a DataFrame
    styler = corr.style.background_gradient(cmap='coolwarm')  # styler is a Styler
    display(styler)  # using Jupyter's display() function

display_corr_matrix_custom()
David
  • 513
  • 7
  • 26
brentertainer
  • 2,118
  • 1
  • 6
  • 15
  • Thanks for your answer! Actually, I'm looking for a solution different than returning it (if possible). I've edited my question with further details. – David Jul 23 '19 at 15:00
  • 1
    @David Have you tried displaying the styler from inside the function? Try doing that instead of returning the styler. I see you have copied code from the link you posted. That code won't work as you expect because it was meant to run as a script, not in the scope of a function. – brentertainer Jul 23 '19 at 15:09
  • oh, my bad! I definitely had to think more about what I was doing. I assumed that the style was somehow modified inplace in the df, but clearly pandas df does not embed a style (hence, `display.display(corr) does not displayed what I wanted). Displaying the styler indeed works! Thanks! – David Jul 23 '19 at 15:17
  • @David Great! I have amended my response. – brentertainer Jul 23 '19 at 15:22