Как построить график ошибок только с положительной стороны в Seaborn? - PullRequest
0 голосов
/ 22 апреля 2020

Я пытаюсь построить диаграмму, и мне нужно решить некоторые проблемы, извините, но я новичок в языке программирования. Первый: как построить только один график? Я получил этот пример из inte rnet, и когда на графике для каждого кода есть две цифры и два из них пустые.

Второй: можно ли построить только положительную полосу ошибок?
Третий: возможно ли построить эти две диаграммы рядом на одной фигуре?

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


Treat1 =pd.DataFrame({'Treatment': 1, 'weight': np.random.randint(low=1, high=100, size=40)})              
Treat2 =pd.DataFrame({'Treatment': 2, 'weight': np.random.randint(low=1, high=100, size=40)}) 

df = pd.concat([Treat1, Treat2])
Treat3 =pd.DataFrame({'Treatment': 1, 'weight': np.random.randint(low=100, high=300, size=40)})              
Treat4 =pd.DataFrame({'Treatment': 2, 'weight': np.random.randint(low=100, high=300, size=40)}) 

df2 = pd.concat([Treat3, Treat4])

sns.set(style="ticks")
fig, ax = plt.subplots()

color_map = dict(pos="indianred", neg="steelblue")
g = sns.catplot(x= "Treatment", y="weight",  hue="Treatment", capsize=.07, ci ="sd", 
                data=df,  kind="bar", palette = 'coolwarm', edgecolor="white")
plt.text(-0.22,99, "B")
plt.text(1.18,99, "A")
plt.ylabel('weight, kg')
plt.xticks([-0.2, 1.2], ['Group 1', 'Group 2'])
plt.ylim(0, 100)

color_map = dict(pos="indianred", neg="steelblue")
g = sns.catplot(x= "Treatment", y="weight",  hue="Treatment", capsize=.07, ci ="sd", 
                data=df2,  kind="bar", palette = 'coolwarm', edgecolor="white")
plt.text(-0.22,300, "B")
plt.text(1.18,300, "A")
plt.ylabel('weight, kg')
plt.xticks([-0.2, 1.2], ['Group 1', 'Group 2'])
plt.ylim(0, 300)

Большое вам спасибо!

1 Ответ

0 голосов
/ 22 апреля 2020

Seaborn catplot - это график уровня фигуры, который создает и занимает новую фигуру. Чтобы иметь такой сюжет как подзаговор, можно вызвать sns.barplot напрямую. * * * * * * * * * * *

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * '' * '] получает легенду, которая в данном случае является излишней, но может быть удалена.

видна только верхняя полоса ошибок, прямоугольники полос могут быть нанесены поверх них. Об этом заботится zorder больше, чем zorder строк панели ошибок (2).

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

Treat1 = pd.DataFrame({'Treatment': 1, 'weight': np.random.randint(low=1, high=100, size=40)})
Treat2 = pd.DataFrame({'Treatment': 2, 'weight': np.random.randint(low=1, high=100, size=40)})
df1 = pd.concat([Treat1, Treat2])

Treat3 = pd.DataFrame({'Treatment': 1, 'weight': np.random.randint(low=100, high=300, size=40)})
Treat4 = pd.DataFrame({'Treatment': 2, 'weight': np.random.randint(low=100, high=300, size=40)})
df2 = pd.concat([Treat3, Treat4])

sns.set(style="ticks")
fig, axs = plt.subplots(ncols=2, figsize=(10, 4))

for ax, df, height in zip(axs, [df1, df2], [100, 300]):

    color_map = {1: "indianred", 2: "steelblue"}
    g = sns.barplot(x="Treatment", y="weight", hue="Treatment", capsize=.07, ci="sd",
                    data=df, palette=color_map, edgecolor="white", ax=ax)
    g.legend_.remove()
    for bar in g.patches:
        bar.set_zorder(3)
    ax.text(-0.2, height * 0.95, "B", ha='center')
    ax.text(1.2, height * 0.95, "A", ha='center')
    ax.set_ylabel('weight, kg')
    ax.set_xticks([-0.2, 1.2])
    ax.set_xticklabels(['Group 1', 'Group 2'])
    ax.set_ylim(0, height)

plt.tight_layout()
plt.show()

example plot

PS: Обратите внимание, что код может быть несколько упрощен, если вы не используете hue=. Это также ставит бары в более логичное положение.


fig, axs = plt.subplots(ncols=2, figsize=(10, 4))

for ax, df, height in zip(axs, [df1, df2], [100, 300]):

    color_map = {1: "indianred", 2: "steelblue"}
    g = sns.barplot(x="Treatment", y="weight", capsize=.07, ci="sd",
                    data=df, palette=color_map, edgecolor="white", ax=ax)
    for bar in g.patches:
        bar.set_zorder(3)
    ax.text(0, height * 0.97, "B", ha='center', va='top')
    ax.text(1, height * 0.97, "A", ha='center', va='top')
    ax.set_ylabel('weight, kg')
    ax.set_ylim(0, height)
    ax.set_xticklabels(['Group 1', 'Group 2'])

plt.tight_layout()
plt.show()

second plot

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