【问题标题】:Matplotlib/Seaborn shareX creates wrong x-labels for all subplots with string x-axis valuesMatplotlib/Seaborn shareX 为所有带有字符串 x 轴值的子图创建错误的 x 标签
【发布时间】:2018-10-12 23:58:18
【问题描述】:

我正在使用 for 循环创建子图,当我打开“sharex”时,所有子图的 x 标签都不正确并与最后一个子图匹配。我希望它为每个可用标签创建一个刻度。

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns


df = pd.DataFrame({
     'letters' : ['A','A','A', 'B','B','B', 'C','C','C', 'D','D','D'],
     'values' : [1, 2, 3, 3, 2, 1, 2, 3, 1, 2, 3, 4],
     'options': ['O 1', 'O 2', 'O 3', 'O 3', 'O 2', 'O 1',
                 'O 2','O 3','O 1','O 2','O 3','O 4'],
                 })

list_letters = ['A', 'B', 'C', 'D']

fig,axes = plt.subplots(nrows = 1, ncols = len(list_letters), sharey = True, sharex = True)
for letter in list_letters:
    index = list_letters.index(letter)
    df2 = df[(df['letters'] == letter)]
    sns.scatterplot(x="options", y="values",data = df2,
              hue = 'options', ax=axes[index], legend = False)

    axes[index].set_title(letter, rotation = 60, verticalalignment = 'bottom', ha = 'left')

我专门制作了数据框,因此选项 O1 的所有“字母”的值为 1。 O2、O3 和 O4 相同。

关闭 shareX (False):

打开 shareX (True):

注意这些值如何与选项不正确对应,只有 3 个标签,并且当 shareX 关闭时,所有子图都与最后一个子图顺序匹配。

这是字符串 x 轴的问题。如果我将“选项”列更改为数值,一切正常。见这里:

有没有办法通过for循环创建子图,打开ShareX,有四个标签,O1、O2、O3、O4,并且所有的值都正确排列? p>

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    很遗憾,目前无法预先确定轴的单位。这使得绘制多个分类数据集变得很麻烦。
    一个 hacky 解决方法是以预期的顺序在轴上绘制一些东西,然后将其删除。这是通过下面代码中的prepare_axes 函数完成的。

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    df = pd.DataFrame({
         'letters' : ['A','A','A', 'B','B','B', 'C','C','C', 'D','D','D'],
         'values' : [1, 2, 3, 3, 2, 1, 2, 3, 1, 2, 3, 4],
         'options': ['O 1', 'O 2', 'O 3', 'O 3', 'O 2', 'O 1',
                     'O 2','O 3','O 1','O 2','O 3','O 4'],
                     })
    
    list_letters = ['A', 'B', 'C', 'D']
    
    def prepare_axes(x, ax):
        ax.autoscale(False)
        line, = ax.plot(x, np.zeros(len(x)))
        line.remove()
        ax.relim()
        ax.autoscale(True)
    
    # determine all needed categoricals        
    uniqueoptions = df["options"].unique()
    
    fig,axes = plt.subplots(nrows = 1, ncols = len(list_letters), sharey = True, sharex = True)
    for letter in list_letters:
        index = list_letters.index(letter)
        df2 = df[(df['letters'] == letter)]
        _, hue = np.unique(df2["options"].values, return_inverse=True)
        prepare_axes(uniqueoptions, axes[index])
        axes[index].scatter(x="options", y="values", c=hue, data = df2)
    
        axes[index].set_title(letter, rotation = 60, verticalalignment = 'bottom', ha = 'left')
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-25
      • 1970-01-01
      • 2018-05-19
      • 2018-07-26
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      相关资源
      最近更新 更多