facetgrid热图数据保存到目录时出现问题

facetgrid热图数据保存到目录时出现问题

本文介绍了将分组的seaborn facetgrid热图数据保存到目录时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力将我的图表保存到特定的目录中,并具有一定的外观.

以下是示例数据以及到目前为止我已经尝试过的内容

将pandas导入为pd将numpy导入为np导入迭代工具将 seaborn 作为 sns 导入从 matplotlib.colors 导入 ListedColormapprint("seaborn version {}".format(sns .__ version__))#R Python中的expand.grid()函数# https://stackoverflow.com/a/12131385/1135316def expandgrid(* itrs):产品=清单(itertools.product(* itrs))return {'Var{}'.format(i+1):[x[i] for x in product] for i in range(len(itrs))}ltt = ['lt1','lt2']方法=['方法1','方法2','方法3','方法4']标签 = ['label1','label2']时间 = 范围(0,100,10)数据= pd.DataFrame(expandgrid(ltt,方法,标签,时间,时间))data.columns = ['ltt','method','labels','dtsi','rtsi']#data ['nw_score'] = np.random.sample(data.shape [0])数据['nw_score'] = np.random.choice([0,1],data.shape[0])数据出[25]:ltt 方法标签 dtsi rtsi nw_score0 lt1方法1标签1 0 0 01 lt1方法1标签1 0 10 12 lt1 方法 1 标签 1 0 20 13 lt1 方法 1 标签 1 0 30 14 lt1 方法 1 标签 1 0 40 1……………………1595 lt2 方法 4 标签 2 90 50 01596 lt2方法4标签2 90 60 01597 lt2方法4标签2 90 70 01598 lt2方法4标签2 90 80 01599 lt2方法4标签2 90 90 0label_fill = {0:'red',1:'blue'}定义方面(数据,颜色):data = data.pivot(index="dtsi", columns='rtsi', values='nw_score')g = sns.heatmap(data, cmap=ListedColormap(['red', 'blue']), cbar=False,annot=True)对于 data.ltt.unique() 中的 l:# 打印(升)使用 sns.plotting_context(font_scale=5.5):g = sns.FacetGrid(data,row ="labels",col ="method + l",size = 2,Aspect = 1,margin_titles = False)g = g.map_dataframe(facet)g.add_legend()#g.set(xlabel ='common xlabel',ylabel ='common ylabel')#g.set_titles(col_template="{col_name}", fontweight='bold', fontsize=18)g.set_titles(template =")对于 ax,m in zip(g.axes[0,:],methods):ax.set_title(m,fontweight ='bold',fontsize = 12)对于 ax,l in zip(g.axes[:,0],labels):ax.set_ylabel(l,fontweight ='bold',fontsize = 12,rotation = 0,ha ='right',va ='center')#g.fig.tight_layout()save_results_to ='D:/图'如果不是 os.path.exists(save_results_to):os.makedirs(save_results_to)g.savefig(save_results_to + l +'.png',dpi = 300)

当我运行上面的代码时,我收到一个错误提示

ValueError:索引包含重复的条目,无法重塑

预期的图形格式

解决方案

问题来自于您试图遍历两个 ltt 级别的事实,但是您没有过滤您的在这些级别上的数据库.

 for l in data.ltt.unique():g = sns.FacetGrid(data [data.ltt == l],....)

此外,您还与变量 l 冲突,该变量一次用于 ltt 级别,而第二次在循环中用于行标签.尝试在代码中使用更具描述性的变量名称.

这是完整的工作代码:

将pandas导入为pd将numpy导入为np导入迭代工具将 seaborn 作为 sns 导入从 matplotlib.colors 导入 ListedColormapprint("seaborn version {}".format(sns .__ version__))#R Python中的expand.grid()函数# https://stackoverflow.com/a/12131385/1135316def expandgrid(* itrs):产品=清单(itertools.product(* itrs))return {'Var{}'.format(i+1):[x[i] for x in product] for i in range(len(itrs))}ltt = ['lt1','lt2']方法=['方法1','方法2','方法3','方法4']标签= ['label1','label2']时间 = 范围(0,100,10)数据= pd.DataFrame(expandgrid(ltt,方法,标签,时间,时间))data.columns = ['ltt','method','labels','dtsi','rtsi']#data['nw_score'] = np.random.sample(data.shape[0])数据['nw_score'] = np.random.choice([0,1],data.shape[0])labels_fill = {0:红色",1:蓝色"}定义方面(数据,颜色):data = data.pivot(index="dtsi", columns='rtsi', values='nw_score')g = sns.heatmap(data,cmap = ListedColormap(['red','blue']),cbar = False,annot = True)对于data.ltt.unique()中的lt:使用 sns.plotting_context(font_scale=5.5):g = sns.FacetGrid(data [data.ltt == lt],row ="labels",col ="method",size = 2,Aspect = 1,margin_titles = False)g = g.map_dataframe(facet)g.add_legend()g.set_titles(template="")对于斧头,zip 中的方法(g.axes[0,:],methods):ax.set_title(方法,fontweight ='bold',fontsize = 12)对于斧头,zip 中的标签(g.axes[:,0],labels):ax.set_ylabel(label,fontweight ='bold',fontsize = 12,rotation = 0,ha ='right',va ='center')g.fig.suptitle(lt, fontweight='bold', fontsize=12)g.fig.tight_layout()g.fig.subplots_adjust(top=0.8) # 为标题留出一些空间g.savefig(lt+'.png', dpi=300)

lt1.png

lt2.png

I've been struggling to save my graphs to the specific directory with some certaion look.

Here is the example data and what I've tried so far

import pandas as pd
import numpy as np
import itertools
import seaborn as sns
from matplotlib.colors import ListedColormap

print("seaborn version {}".format(sns.__version__))
# R expand.grid() function in Python
# https://stackoverflow.com/a/12131385/1135316
def expandgrid(*itrs):
   product = list(itertools.product(*itrs))
   return {'Var{}'.format(i+1):[x[i] for x in product] for i in range(len(itrs))}




ltt= ['lt1','lt2']

methods=['method 1', 'method 2', 'method 3', 'method 4']
labels = ['label1','label2']
times = range(0,100,10)
data = pd.DataFrame(expandgrid(ltt,methods,labels, times, times))
data.columns = ['ltt','method','labels','dtsi','rtsi']
#data['nw_score'] = np.random.sample(data.shape[0])
data['nw_score'] = np.random.choice([0,1],data.shape[0])

data
Out[25]:
      ltt    method  labels  dtsi  rtsi  nw_score
0     lt1  method 1  label1     0     0         0
1     lt1  method 1  label1     0    10         1
2     lt1  method 1  label1     0    20         1
3     lt1  method 1  label1     0    30         1
4     lt1  method 1  label1     0    40         1
  ...       ...     ...   ...   ...       ...
1595  lt2  method 4  label2    90    50         0
1596  lt2  method 4  label2    90    60         0
1597  lt2  method 4  label2    90    70         0
1598  lt2  method 4  label2    90    80         0
1599  lt2  method 4  label2    90    90         0




labels_fill = {0:'red',1:'blue'}

def facet(data,color):
    data = data.pivot(index="dtsi", columns='rtsi', values='nw_score')
    g = sns.heatmap(data, cmap=ListedColormap(['red', 'blue']), cbar=False,annot=True)


for l in data.ltt.unique():

#    print(l)

    with sns.plotting_context(font_scale=5.5):
        g = sns.FacetGrid(data,row="labels", col="method+l", size=2, aspect=1,margin_titles=False)
        g = g.map_dataframe(facet)
        g.add_legend()
       # g.set(xlabel='common xlabel', ylabel='common ylabel')
        #g.set_titles(col_template="{col_name}", fontweight='bold', fontsize=18)
        g.set_titles(template="")

        for ax,m in zip(g.axes[0,:],methods):
            ax.set_title(m, fontweight='bold', fontsize=12)
        for ax,l in zip(g.axes[:,0],labels):
            ax.set_ylabel(l, fontweight='bold', fontsize=12, rotation=0, ha='right', va='center')

     #   g.fig.tight_layout()

    save_results_to = 'D:/plots'

    if not os.path.exists(save_results_to):
        os.makedirs(save_results_to)


    g.savefig(save_results_to + l+  '.png', dpi = 300)

When I ran the code above I'm getting an error which says

the expected graph format

解决方案

The problems comes from the fact that you are trying to loop through the two ltt levels, but then you don't filter your database on those levels.

for l in data.ltt.unique():
    g = sns.FacetGrid(data[data.ltt==l], ....)

Also, you have a conflict with the variable l that's used once for the ltt level and the second time in the loop for the row labels. Try using more descriptive variable names in your code.

Here is the full working code:

import pandas as pd
import numpy as np
import itertools
import seaborn as sns
from matplotlib.colors import ListedColormap

print("seaborn version {}".format(sns.__version__))
# R expand.grid() function in Python
# https://stackoverflow.com/a/12131385/1135316
def expandgrid(*itrs):
   product = list(itertools.product(*itrs))
   return {'Var{}'.format(i+1):[x[i] for x in product] for i in range(len(itrs))}




ltt= ['lt1','lt2']

methods=['method 1', 'method 2', 'method 3', 'method 4']
labels = ['label1','label2']
times = range(0,100,10)
data = pd.DataFrame(expandgrid(ltt,methods,labels, times, times))
data.columns = ['ltt','method','labels','dtsi','rtsi']
#data['nw_score'] = np.random.sample(data.shape[0])
data['nw_score'] = np.random.choice([0,1],data.shape[0])

labels_fill = {0:'red',1:'blue'}

def facet(data,color):
    data = data.pivot(index="dtsi", columns='rtsi', values='nw_score')
    g = sns.heatmap(data, cmap=ListedColormap(['red', 'blue']), cbar=False,annot=True)


for lt in data.ltt.unique():
    with sns.plotting_context(font_scale=5.5):
        g = sns.FacetGrid(data[data.ltt==lt],row="labels", col="method", size=2, aspect=1,margin_titles=False)
        g = g.map_dataframe(facet)
        g.add_legend()
        g.set_titles(template="")

        for ax,method in zip(g.axes[0,:],methods):
            ax.set_title(method, fontweight='bold', fontsize=12)
        for ax,label in zip(g.axes[:,0],labels):
            ax.set_ylabel(label, fontweight='bold', fontsize=12, rotation=0, ha='right', va='center')
        g.fig.suptitle(lt, fontweight='bold', fontsize=12)
        g.fig.tight_layout()
        g.fig.subplots_adjust(top=0.8) # make some room for the title

        g.savefig(lt+'.png', dpi=300)

这篇关于将分组的seaborn facetgrid热图数据保存到目录时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:18