I found and am using @mrandrewandrade great answer to display the correlation coefficients of the boston housing data using a styled panda dataframe in an iPython notebook when I've noticed that the color mapping used in the background_gradient()
isn't calculating correctly for the CHAS
data.
It also looks like some of the values in the B
data are affected as well.
Its correct in the axis passed into the background_gradient(cmap, axis=1)
command but not the other axis. The row axis will work is you change that line to axis=0
. All the other table cells seem to calculate fine.
Can someone help figure out the problem, I'm stumped as to what is happening and how to avoid it?
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# load Boston housing data into a dataframe
from sklearn.datasets import load_boston
boston = load_boston()
bos = pd.DataFrame(boston.data, columns=boston.feature_names)
bos['MEDV'] = boston.target
bos.head()
# using a styled panda's dataframe from https://stackoverflow.com/a/42323184/1215012
cmap = 'coolwarm'
def magnify():
return [dict(selector="th", props=[("font-size", "7pt")]),
dict(selector="td", props=[('padding', "0em 0em")]),
dict(selector="th:hover", props=[("font-size", "12pt")]),
dict(selector="tr:hover td:hover",
props=[('max-width', '200px'), ('font-size', '12pt')])
]
corr.style.background_gradient(cmap, axis=1)\
.set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
.set_caption("Hover to magify")\
.set_precision(2)\
.set_table_styles(magnify())
To help highlight the issue here is the same data plotted as a seaborn heatmap:
# calculating and plotting the correlation coeff's using a seaborn heatmap
corr = bos.corr()
sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, cmap='coolwarm')
I found this question by having the same issue. This answer solved my problem.
In short, it seems there is no way to use the actual backgroud_gradient DataFrame method, but is not too complicated to achieve the effect you're looking for with a custom function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With