条形图内部条形图 – pandas – css

对于我的一个pandas数据框(python)的html表示,我想创build一些类似于尽可能多的图像(使用Excel创build),也就是给定一个数字序列,创buildINSIDE A TABLE ,一些水平如果值大于零,条形图将变为绿色,如果它们低于零,并且轴中的“零”点根据提供的数据进行dynamic重新调整,则为红色。 我最接近的是使用pandas本地文书由下面的代码( http://pandas.pydata.org/pandas-docs/stable/style.html ) 在这里输入图像描述

#done in Jupyter from pandas import DataFrame df = pd.DataFrame([-0.02, 0.03, 0.04, -0.05], columns=['A']) more_than_zero = df.loc[df.loc[:,'A'] >= 0].index.values.tolist() less_than_zero = df.loc[df.loc[:,'A'] < 0].index.values.tolist() df.style.bar(subset=pd.IndexSlice[more_than_zero,'A'], color='#d65f5f') #df.style.bar(subset=pd.IndexSlice[less_than_zero, 'B'], color='#7fff00') 

现在没有办法使用pandas开箱即用(我会尽快实现),但现在这里有一个猴子补丁的解决scheme:

 def _bar_center_zero(self, s, color_positive, color_negative, width): # Either the min or the max should reach the edge (50%, centered on zero) m = max(abs(s.min()),abs(s.max())) normed = s * 50 * width / (100 * m) base = 'width: 10em; height: 80%;' attrs_neg = (base+ 'background: linear-gradient(90deg, transparent 0%, transparent {w}%, {c} {w}%, ' '{c} 50%, transparent 50%)') attrs_pos = (base+ 'background: linear-gradient(90deg, transparent 0%, transparent 50%, {c} 50%, {c} {w}%, ' 'transparent {w}%)') return [attrs_pos.format(c=color_positive, w=(50+x)) if x > 0 else attrs_neg.format(c=color_negative, w=(50+x)) for x in normed] def bar_excel(self, subset=None, axis=0, color_positive='#5FBA7D', color_negative='#d65f5f', width=100): """ Color the background ``color`` proptional to the values in each column. Excludes non-numeric data by default. .. versionadded:: 0.17.1 Parameters ---------- subset: IndexSlice, default None a valid slice for ``data`` to limit the style application to axis: int color_positive: str color_negative: str width: float A number between 0 or 100. The largest value will cover ``width`` percent of the cell's width Returns ------- self : Styler """ #subset = _maybe_numeric_slice(self.data, subset) #subset = _non_reducing_slice(subset) self.apply(self._bar_center_zero, axis=axis, subset=subset, color_positive=color_positive, color_negative=color_negative, width=width) return self 

猴子 – 这个补丁到Styler类:

 pd.formats.style.Styler._bar_center_zero = _bar_center_zero pd.formats.style.Styler.bar_excel = bar_excel 

现在你可以使用它:

 df = pd.DataFrame([-0.02, 0.03, 0.04, -0.05], columns=['A']) df.style.bar_excel(color_positive='#5FBA7D', color_negative='#d65f5f') 

熊猫条形图sparkline like Excel


更新:

我从那以后在GitHub上创build了一个pull请求,在这里我实现了这个以及“dynamic”居中的选项( align='mid' )。

您可以通过指定选项align和取决于您的数据types得到的结果栏如下所示:

在这里输入图像说明