Python seaborn.catplot() Examples

The following are 10 code examples of seaborn.catplot(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module seaborn , or try the search function .
Example #1
Source File: analysis.py    From dl-eeg-review with MIT License 6 votes vote down vote up
def _plot_results_per_citation_task(results_df, save_cfg):
    """Plot scatter plot of accuracy for each condition and task.
    """
    fig, ax = plt.subplots(figsize=(save_cfg['text_width'], 
                                    save_cfg['text_height'] * 1.3))
    # figsize = plt.rcParams.get('figure.figsize')
    # fig, ax = plt.subplots(figsize=(figsize[0], figsize[1] * 4))
    # Need to make the graph taller otherwise the y axis labels are on top of
    # each other.
    sns.catplot(y='citation_task', x='Result', hue='model_type', data=results_df, 
                ax=ax)
    ax.set_xlabel('accuracy')
    ax.set_ylabel('')
    plt.tight_layout()

    if save_cfg is not None:
        savename = 'reported_results'
        fname = os.path.join(save_cfg['savepath'], savename)
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return ax 
Example #2
Source File: analysis.py    From dl-eeg-review with MIT License 6 votes vote down vote up
def _plot_results_accuracy_diff_scatter(results_df, save_cfg):
    """Plot difference in accuracy for each condition/task as a scatter plot.
    """
    fig, ax = plt.subplots(figsize=(save_cfg['text_width'], 
                                    save_cfg['text_height'] * 1.3))
    # figsize = plt.rcParams.get('figure.figsize')
    # fig, ax = plt.subplots(figsize=(figsize[0], figsize[1] * 2))
    sns.catplot(y='Task', x='acc_diff', data=results_df, ax=ax)
    ax.set_xlabel('Accuracy difference')
    ax.set_ylabel('')
    ax.axvline(0, c='k', alpha=0.2)
    plt.tight_layout()

    if save_cfg is not None:
        savename = 'reported_accuracy_diff_scatter'
        fname = os.path.join(save_cfg['savepath'], savename)
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return ax 
Example #3
Source File: analysis.py    From dl-eeg-review with MIT License 5 votes vote down vote up
def plot_hardware(df, save_cfg=cfg.saving_config):
    """Plot bar graph showing the hardware used in the study.
    """
    col = 'EEG Hardware'
    hardware_df = ut.split_column_with_multiple_entries(
        df, col, ref_col='Citation', sep=',', lower=False)

    # Remove N/Ms because they make it hard to see anything
    hardware_df = hardware_df[hardware_df[col] != 'N/M']
    
    # Add low cost column
    hardware_df['Low-cost'] = False
    low_cost_devices = ['EPOC (Emotiv)', 'OpenBCI (OpenBCI)', 'Muse (InteraXon)', 
                        'Mindwave Mobile (Neurosky)', 'Mindset (NeuroSky)']
    hardware_df.loc[hardware_df[col].isin(low_cost_devices), 
                    'Low-cost'] = True

    fig, ax = plt.subplots(figsize=(save_cfg['text_width'] / 4 * 2, 
                                    save_cfg['text_height'] / 5 * 2))
    sns.countplot(hue=hardware_df['Low-cost'], y=hardware_df[col], ax=ax,
                  order=hardware_df[col].value_counts().index, 
                  dodge=False)
    # sns.catplot(row=hardware_df['low_cost'], y=hardware_df['hardware'])
    ax.set_xlabel('Number of papers')
    ax.set_ylabel('')
    plt.tight_layout()

    if save_cfg is not None:
        fname = os.path.join(save_cfg['savepath'], 'hardware')
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return ax 
Example #4
Source File: attention_allocation_experiment_plotting.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def plot_discovered_missed_clusters(dataframe, file_path=''):
  """Plot location clusters comparing agents missed and discovered incidents."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.catplot(
      x='param_value',
      y='missed_incidents',
      data=dataframe,
      hue='agent_type',
      palette='deep',
      height=plot_height,
      aspect=aspect_ratio,
      s=8,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Missed incidents for each location', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.tight_layout()
  plt.savefig(file_path + '_missed.pdf')

  sns.catplot(
      x='param_value',
      y='discovered_incidents',
      data=dataframe,
      hue='agent_type',
      height=plot_height,
      aspect=aspect_ratio,
      s=8,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered incidents for each location', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.tight_layout()
  plt.savefig(file_path + '_discovered.pdf') 
Example #5
Source File: attention_allocation_experiment_plotting.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def plot_total_miss_discovered(dataframe, file_path=''):
  """Plot bar charts comparing agents total missed and discovered incidents."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.set_style('whitegrid')
  sns.despine()

  sns.catplot(
      x='param_value',
      y='total_missed',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Total missed incidents', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_missed.pdf', bbox_inches='tight')

  sns.catplot(
      x='param_value',
      y='total_discovered',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio,
      legend=False)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Total discovered incidents', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_discovered.pdf', bbox_inches='tight') 
Example #6
Source File: attention_allocation_experiment_plotting.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def plot_discovered_occurred_ratio_range(dataframe, file_path=''):
  """Plot the range of discovered incidents/occurred range between locations."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.set_style('whitegrid')
  sns.despine()

  sns.catplot(
      x='param_value',
      y='discovered/occurred range',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred range', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '.pdf', bbox_inches='tight')

  sns.catplot(
      x='param_value',
      y='discovered/occurred range weighted',
      data=dataframe,
      hue='agent_type',
      kind='bar',
      palette='muted',
      height=plot_height,
      aspect=aspect_ratio)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Delta', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_weighted.pdf', bbox_inches='tight') 
Example #7
Source File: attention_allocation_experiment_plotting.py    From ml-fairness-gym with Apache License 2.0 5 votes vote down vote up
def plot_discovered_occurred_ratio_locations(dataframe, file_path=''):
  """Plot the discovered incidents/occurred ratio for each location."""
  plot_height = 5
  aspect_ratio = 1.3
  sns.despine()

  sns.set(style='ticks')
  sns.catplot(
      x='param_value',
      y='discovered/occurred',
      data=dataframe,
      hue='agent_type',
      height=plot_height,
      aspect=aspect_ratio,
      s=8)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '.pdf', bbox_inches='tight')

  sns.set(style='ticks')
  sns.catplot(
      x='param_value',
      y='discovered/occurred weighted',
      data=dataframe,
      hue='agent_type',
      height=plot_height,
      aspect=aspect_ratio,
      s=8)
  plt.xlabel('Dynamic factor', fontsize=LARGE_FONTSIZE)
  plt.ylabel('Discovered/occurred weighted', fontsize=LARGE_FONTSIZE)
  plt.xticks(fontsize=MEDIUM_FONTSIZE)
  plt.yticks(fontsize=MEDIUM_FONTSIZE)
  # plt.legend(fontsize=MEDIUM_FONTSIZE, title_fontsize=MEDIUM_FONTSIZE)
  plt.savefig(file_path + '_weighted.pdf', bbox_inches='tight') 
Example #8
Source File: plot.py    From iroko with Apache License 2.0 5 votes vote down vote up
def analyze_pcap(rl_algos, tcp_algos, plt_name, runs, data_dir):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import seaborn as sns

    algos = rl_algos + tcp_algos
    host_rtt = {}
    for algo in algos:
        host_rtt[algo] = process_rtt_files(data_dir, runs, algo)
    pcap_df = pd.DataFrame.from_dict(host_rtt, orient='index')
    pcap_df = pd.melt(pcap_df.reset_index(), id_vars='index',
                      var_name="Metric",
                      value_name="Average RTT (ms)")
    pcap_df = pcap_df.rename(columns={'index': 'Algorithm'})
    # Convert to milliseconds
    # pcap_df = pcap_df.div(1e6)
    fig = sns.catplot(x='Metric', y='Average RTT (ms)',
                      hue="Algorithm", data=pcap_df, kind='bar')
    from itertools import cycle
    hatches = cycle(["/", "-", "+", "x", '-', '+', 'x', 'O', '.'])

    num_locations = len(pcap_df.Metric.unique())
    for i, patch in enumerate(fig.ax.patches):
        # Blue bars first, then green bars
        if i % num_locations == 0:
            hatch = next(hatches)
        patch.set_hatch(hatch)
    plt_name += "_rtt"
    log.info("Saving plot %s" % plt_name)
    plt.savefig(plt_name + ".png", bbox_inches='tight', pad_inches=0.05)
    plt.savefig(plt_name + ".pdf", bbox_inches='tight', pad_inches=0.05)
    plt.gcf().clear() 
Example #9
Source File: analysis.py    From dl-eeg-review with MIT License 4 votes vote down vote up
def _plot_results_accuracy_per_domain(results_df, diff_df, save_cfg):
    """Make scatterplot + boxplot to show accuracy difference by domain.
    """
    fig, axes = plt.subplots(
        nrows=2, ncols=1, sharex=True, 
        figsize=(save_cfg['text_width'], save_cfg['text_height'] / 3), 
        gridspec_kw = {'height_ratios':[5, 1]})

    results_df['Main domain'] = results_df['Main domain'].apply(
        ut.wrap_text, max_char=20)

    sns.catplot(y='Main domain', x='acc_diff', s=3, jitter=True, 
                data=results_df, ax=axes[0])
    axes[0].set_xlabel('')
    axes[0].set_ylabel('')
    axes[0].axvline(0, c='k', alpha=0.2)

    sns.boxplot(x='acc_diff', data=diff_df, ax=axes[1])
    sns.swarmplot(x='acc_diff', data=diff_df, color="0", size=2, ax=axes[1])
    axes[1].axvline(0, c='k', alpha=0.2)
    axes[1].set_xlabel('Accuracy difference')

    fig.subplots_adjust(wspace=0, hspace=0.02)
    plt.tight_layout()

    logger.info('Number of studies included in the accuracy improvement analysis: {}'.format(
        results_df.shape[0]))
    median = diff_df['acc_diff'].median()
    iqr = diff_df['acc_diff'].quantile(.75) - diff_df['acc_diff'].quantile(.25)
    logger.info('Median gain in accuracy: {:.6f}'.format(median))
    logger.info('Interquartile range of the gain in accuracy: {:.6f}'.format(iqr))
    best_improvement = diff_df.nlargest(3, 'acc_diff')
    logger.info('Best improvement in accuracy: {}, in {}'.format(
        best_improvement['acc_diff'].values[0], 
        best_improvement['Citation'].values[0]))
    logger.info('Second best improvement in accuracy: {}, in {}'.format(
        best_improvement['acc_diff'].values[1], 
        best_improvement['Citation'].values[1]))
    logger.info('Third best improvement in accuracy: {}, in {}'.format(
        best_improvement['acc_diff'].values[2], 
        best_improvement['Citation'].values[2]))

    if save_cfg is not None:
        savename = 'reported_accuracy_per_domain'
        fname = os.path.join(save_cfg['savepath'], savename)
        fig.savefig(fname + '.' + save_cfg['format'], **save_cfg)

    return axes 
Example #10
Source File: distanceWeightCalculation_raster2Polygon.py    From python-urbanPlanning with MIT License 4 votes vote down vote up
def visualisationDF(df):    
    dataFrameInfoPrint(df)
    #graph-01
    # df['shapelyArea'].plot.hist(alpha=0.5)    
    #graph-02
    # df['shapelyArea'].plot.kde()    
    #graph-03
    # df[['shapelyLength','shapeIdx']].plot.scatter('shapelyLength','shapeIdx')    
    #normalize data in a range of columns
    cols_to_norm=['shapeIdx', 'FRAC']
    df[cols_to_norm]=df[cols_to_norm].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
    
    a='shapeIdx'
    b='FRAC'
    c='park_class'
    
    #graph-04
    # sns.jointplot(a,b,df,kind='hex')
    
    #graph-05
    # sns.jointplot(a, b, df, kind='kde')
    
    #graph-06
    # sns.catplot(x='park_class',y=a,data=df)
    
    #graph-07
    '''
    # Initialize the figure
    f, ax = plt.subplots()
    sns.despine(bottom=True, left=True)
    # Show each observation with a scatterplot
    sns.stripplot(x=a, y=c, hue=c,data=df, dodge=True, alpha=.25, zorder=1)    
    # Show the conditional means
    sns.pointplot(x=a, y=c, hue=c,data=df, dodge=.532, join=False, palette="dark",markers="d", scale=.75, ci=None)
    # Improve the legend 
    handles, labels = ax.get_legend_handles_labels()
    ax.legend(handles[3:], labels[3:], title=b,handletextpad=0, columnspacing=1,loc="lower right", ncol=3, frameon=True)
    '''
    
    #graph-08
    # sns.catplot(x=c,y=a,data=df,kind='box')
    
    #graph-09
    # sns.catplot(x=c,y=a,data=df,kind='violin')
    
    #graph-10
    '''
    f, axs = plt.subplots(1, 2, figsize=(12, 6))
    # First axis    
    df[b].plot.hist(ax=axs[0])
    # Second axis
    df[b].plot.kde(ax=axs[1])
    # Title
    f.suptitle(b)
    # Display
    plt.show()
    '''        

#从新定义栅格投影,参考投影为vector .shp文件