Matplotlib / Seaborn shareX为具有字符串x轴值的所有子图创建错误的x标签

时间:2018-10-12 23:58:19

标签: python matplotlib seaborn

我正在使用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(错误):
With shareX turned off

打开shareX(正确):
With shareX turned on

请注意值与选项的正确性如何,只有3个标签,并且当shareX禁用时,所有子图都与最后一个子图顺序匹配。

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

是否可以通过for循环创建子图,打开ShareX并具有四个标签O1,O2,O3,O4,并且所有值正确排列?

1 个答案:

答案 0 :(得分:0)

不幸的是,当前尚无法预先确定轴的单位。这使得绘制多个类别数据集变得麻烦。
一种有针对性的解决方法是按预期顺序在轴上绘制一些东西,然后再将其删除。这是通过下面的代码中的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()

enter image description here