Как отрегулировать xlim, увеличить расстояние между каждым графиком и установить заголовок для «хребта» от seaborn - PullRequest
0 голосов
/ 11 января 2019

Я бы хотел выполнить следующие действия на основе примера «морского хребта» (https://seaborn.pydata.org/examples/kde_ridgeplot.html):

).
  1. Настройте xlim, чтобы увеличить расстояние между заголовком ошибки, например «Error2 - abc ...» и сам график
  2. Увеличить расстояние между каждым графиком
  3. Установить заголовок для всего сюжета

Я пробовал с sns.plt.xlim(-10, 3), что приводит к ошибке. А вот и весь мой код:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})


errorNames = ['Error 1 - abc.....',
              'Error 2 - abc.....',
              'Error 3 - abc.....',
              'Error 4 - abc.....',
              'Error 5 - abc.....',
              'Error 6 - abc.....',
              'Error 7 - abc.....',
              'Error 8 - abc.....',
              'Error 9 - abc.....',
              'Error 10 - abc.....',
              'Error 11 - abc.....',
              'Error 12 - abc.....',
              'Error 13 - abc.....']


# Create the data
rs = np.random.RandomState(1979)
x = rs.randn(650)
#g = np.tile(list("ABCDEFGHIJKLM"), 50)
g = np.tile(list(errorNames), 50)

df = pd.DataFrame(dict(x=x, g=g))
#m = df.g.map(ord)
#df["x"] += m

# Initialize the FacetGrid object
pal = sns.cubehelix_palette(10, rot=-.25, light=.7)
g = sns.FacetGrid(df, row="g", hue="g", aspect=15, height=.5, palette=pal)

# Draw the densities in a few steps
g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=1, lw=1.5, bw=.2)
g.map(sns.kdeplot, "x", clip_on=False, color="w", lw=2, bw=.2)
g.map(plt.axhline, y=0, lw=2, clip_on=False)


# sns.plt.xlim(-10, 3)


# Define and use a simple function to label the plot in axes coordinates
def label(x, color, label):
    ax = plt.gca()
    ax.text(0, .2, label, fontweight="bold", color=color,
            ha="left", va="center", transform=ax.transAxes)


g.map(label, "x")

# Set the subplots to overlap 
# Erst hier wird geplotted
g.fig.subplots_adjust(hspace=-.25)


# Remove axes details that don't play well with overlap
g.set_titles("")
g.set(yticks=[])
g.despine(bottom=True, left=True)

Ответы [ 2 ]

0 голосов
/ 11 января 2019

Ниже приведен один из способов решения всех трех вопросов:

  • g.set(xlim=(-4, 3)) устанавливает x-пределы
  • ax.text(0, .25,...) Более высокое смещение 0,25 вместо 0,2 правильно позиционирует имена ошибок.
  • plt.suptitle('Main title') помещает главный заголовок вверху рисунка.

g.set(xlim=(-4, 3))

def label(x, color, label):
    ax = plt.gca()
    ax.text(0, .25, label, fontweight="bold", color=color,
            ha="left", va="center", transform=ax.transAxes)

g.map(label, "x")
g.fig.subplots_adjust(hspace=-.25)

# Remove axes details that don't play well with overlap
g.set_titles("")
g.set(yticks=[])
g.despine(bottom=True, left=True)
plt.suptitle('Main title')

enter image description here

0 голосов
/ 11 января 2019

Для 1) вы можете изменить пределы x в том же вызове на g.set при удалении yticks:

g.set(yticks=[], xlim=[-5, 3])

Для 2) вы можете просто настроить значение hspace в subplots_adjust

Для 3) вы можете создать suptitle для фигуры:

g.fig.suptitle("Some title")

Это дает что-то вроде:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...