Python: изменение визуальных параметров репо ptitprince, полученных из seaborn и matplotlib - PullRequest
0 голосов
/ 14 марта 2019

Я использую github-репозиторий ptitprince, созданный на основе seaborn и matplotlib, для генерации графиков.

Например, этот код использует репозиторий ptitprince:

# coding: utf8

import pandas as pd
import ptitprince as pt
import seaborn as sns
import os
import matplotlib.pyplot as plt
#sns.set(style="darkgrid")
#sns.set(style="whitegrid")
#sns.set_style("white")
sns.set(style="whitegrid",font_scale=2)
import matplotlib.collections as clt

df = pd.read_csv ("u118phag.csv", sep= ",")
df.head()

savefigs = True
figs_dir = 'figs'

if savefigs:
    # Make the figures folder if it doesn't yet exist
    if not os.path.isdir('figs'):
        os.makedirs('figs')

#automation
f, ax = plt.subplots(figsize=(4, 5))
#f.subplots_adjust(hspace=0,wspace=0)
dx = "Treatment"; dy = "score"; ort = "v"; pal = "Set2"; sigma = .2
ax=pt.RainCloud(x = dx, y = dy, data = df, palette = pal, bw = sigma,
                 width_viol = .6, ax = ax, move=.2, offset=.1, orient = ort, pointplot = True)
f.show()

if savefigs:
    f.savefig('figs/figure20.png', bbox_inches='tight', dpi=500)

, который генерирует следующий график

Необработанный код, не использующий ptitprince, выглядит следующим образом и выдает тот же график, что и выше:

# coding: utf8

import pandas as pd
import ptitprince as pt
import seaborn as sns
import os
import matplotlib.pyplot as plt
#sns.set(style="darkgrid")
#sns.set(style="whitegrid")
#sns.set_style("white")
sns.set(style="whitegrid",font_scale=2)
import matplotlib.collections as clt

df = pd.read_csv ("u118phag.csv", sep= ",")
df.head()

savefigs = True
figs_dir = 'figs'

if savefigs:
    # Make the figures folder if it doesn't yet exist
    if not os.path.isdir('figs'):
        os.makedirs('figs')

f, ax = plt.subplots(figsize=(7, 5))
dy="Treatment"; dx="score"; ort="h"; pal = sns.color_palette(n_colors=1)

#adding color
pal = "Set2"
f, ax = plt.subplots(figsize=(7, 5))
ax=pt.half_violinplot( x = dx, y = dy, data = df, palette = pal, bw = .2, cut = 0.,
                      scale = "area", width = .6, inner = None, orient = ort)
ax=sns.stripplot( x = dx, y = dy, data = df, palette = pal, edgecolor = "white",
                 size = 3, jitter = 1, zorder = 0, orient = ort)
ax=sns.boxplot( x = dx, y = dy, data = df, color = "black", width = .15, zorder = 10,\
            showcaps = True, boxprops = {'facecolor':'none', "zorder":10},\
            showfliers=True, whiskerprops = {'linewidth':2, "zorder":10},\
               saturation = 1, orient = ort)


if savefigs:
    f.savefig('figs/figure21.png', bbox_inches='tight', dpi=500)

Теперь я пытаюсь выяснить, как изменить график, чтобы я мог (1) переместить графики ближе друг к другу, чтобы между ними было не так много пустого пространства, и (2) сдвинуть ось x направо, так что я могу сделать график распределения (скрипка) шире, не разрезая его пополам по оси y.

Я попытался поиграться с subplots_adjust(), как вы можете видеть в первом блоке кода, но я получаю сообщение об ошибке. Я не могу понять, как правильно использовать эту функцию, или даже если это на самом деле сблизит разные графики.

Я также знаю, что могу увеличить размер распределения, увеличив это значение width = .6, но если я увеличу его слишком высоко, график распределения начнет срезаться по оси Y. Я не могу понять, нужно ли мне корректировать весь график, используя plt.subplots, или мне нужно переместить каждый отдельный график.

Какой-нибудь совет или рекомендации о том, как изменить визуальные элементы графика? Некоторое время я смотрел на это и не могу понять, как сделать так, чтобы seaborn / matplotlib хорошо играли с ptitprince.

...