【问题标题】:making seaborn heatmap from DataFrame plot to be aware of data ranges从 DataFrame 图中制作 seaborn 热图以了解数据范围
【发布时间】:2019-08-12 10:56:42
【问题描述】:

如何制作 seaborn 热图(从 pandas DataFrame 图创建)以了解数据范围? IE。当我将鼠标指针悬停在绘图上时,我可以在绘图窗口的右下角看到 "x= y=",而我想在绘图上查看我所在的点的坐标将鼠标悬停在(例如,"x=25.6, y=3.3")上,当然假设输入 DataFrame 包含一个 2D 直方图,每个轴上具有相同大小的 bin。

或者,也许我可以用不同的方式创建这样的情节来达到同样的效果?例如,使用 ax.hist2d 我可以直接使用它,但我希望能够使用每个 bin 的自定义代码内容进行计算,并使其有效地成为热图(使用 bin 内容的颜色编码)。

import numpy as np 
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
Index = [ 1.0,  2.0,  3.0,  4.0,  5.0]
Cols  = [10.0, 20.0, 30.0, 40.0, 50.0]
df = pd.DataFrame(abs(np.random.randn(5, 5)), 
    index=Index, columns=Cols)
plt.close(1)
fig,ax = plt.subplots(num=1)
sns.heatmap(df, annot=True)
plt.show(block=False)

感谢您的帮助!

【问题讨论】:

    标签: pandas matplotlib plot seaborn heatmap


    【解决方案1】:
    from matplotlib.ticker import FixedFormatter
    
    
    class CustomFormatter(FixedFormatter):
        def __init__(self, old):
            super().__init__(old.seq)
    
        def __call__(self, x, pos=None):
            return self.seq[abs(self.locs - x).argmin()]
    
    plt.gca().xaxis.set_major_formatter(CustomFormatter(plt.gca().xaxis.get_major_formatter()))
    plt.gca().yaxis.set_major_formatter(CustomFormatter(plt.gca().yaxis.get_major_formatter()))
    

    【讨论】:

      【解决方案2】:

      如果您将sns.heatmap(...) 替换为ax.imshow(..),那么您就接近了您所需要的。然后您可以将图像的范围设置为您需要的数据范围。

      import numpy as np; np.random.seed(42)
      import pandas as pd
      import matplotlib.pyplot as plt
      
      Index = [ 1.0,  2.0,  3.0,  4.0,  5.0]
      Cols  = [10.0, 20.0, 30.0, 40.0, 50.0]
      df = pd.DataFrame(abs(np.random.randn(5, 5)), 
          index=Index, columns=Cols)
      plt.close(1)
      fig,ax = plt.subplots(num=1)
      dx = np.diff(df.columns)[0]/2
      dy = np.diff(df.index)[0]/2
      extent = [df.columns.min()-dx, df.columns.max()+dx,
                df.index.min()-dy, df.index.max()+dy] 
      ax.imshow(df, extent=extent, aspect="auto")
      
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2021-05-08
        • 2012-08-30
        • 2022-06-22
        • 2023-03-05
        • 2022-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-27
        相关资源
        最近更新 更多