Python воссоздание ноутбука - PullRequest
0 голосов
/ 01 мая 2020

Я пытаюсь воссоздать этот блокнот (python) https://nbviewer.jupyter.org/github/lalelale/profiles_analysis/blob/master/profiles.ipynb

в блокноте Anaconda Jupyter.

В частности, я хочу график ниже. Я ввожу в свой блокнот все данные, как есть, но получаю эту ошибку "barh () отсутствует 1 обязательный позиционный аргумент: 'y'"

Эта ячейка дает мне ошибку.

def compare_word_use(d_contains,g1,g2,g1name,g2name,g1color,g2color,ax):
    g1n=d_contains.loc[g1].sum(axis=0) # for each word, number of users in group g1 who use this word
    g2n=d_contains.loc[g2].sum(axis=0) # for each word, number of users in group g2 who use this word
    df=pd.concat({"g1n":g1n,"g2n":g2n},axis=1).fillna(0)
    df["g1f"]=df["g1n"]/(df["g1n"].sum()) # fraction of g1 users which use given word
    df["g2f"]=df["g2n"]/(df["g2n"].sum()) # fraction of g2 users which use given word
    df["frac12"]=df["g1f"]/(df["g1f"]+df["g2f"])
    df=df[(df["g1n"]+df["g2n"])>=50] # exclude words which are used by too few users
    df=df.sort_values("frac12")

    n=40;
    gap=0.5;

    bottom_df=df["frac12"].head(n)
    top_df=df["frac12"].tail(n)

    # Bottom bars
    bottom_bars_y=np.arange(n)
    ax.barh(bottom=bottom_bars_y,
                width=bottom_df,
                left=0,
                height=1,
                align="center",
                color=g1color,alpha=1)
    ax.barh(bottom=bottom_bars_y,
                width=bottom_df-1,
                left=1,
                height=1,
                align="center",
                color=g2color,alpha=1)

    # Top bars
    top_bars_y=np.arange(n)+gap+n
    ax.barh(bottom=top_bars_y,
                width=top_df,
                left=0,
                height=1,
                align="center",
                color=g1color,alpha=1)
    ax.barh(bottom=top_bars_y,
                width=top_df-1,
                left=1,
                height=1,
                align="center",
                color=g2color,alpha=1)

    ax.axvline(x=0.5,color="k",alpha=0.1,linewidth=5)
    ax.set(xlim=[0,1],
           ylim=[-1,n*2+gap-0.5],
           yticks=np.hstack((bottom_bars_y,top_bars_y)),
           yticklabels=list(bottom_df.index)+list(top_df.index),
           xlabel="fraction of users",
           ylabel="word contained in essays")
    ax.set_title("Relative prevalence of {} ($n={}$) vs {} ($n={}$)\namong users that wrote a given word in essays".format(
                g1name,g1.sum(),g2name,g2.sum()),
                loc="left",fontdict={"fontsize":"medium"})
    ax.text(0.02,top_bars_y[-1],g1name,verticalalignment="center",horizontalalignment="left",size="smaller",color="w")
    ax.text(0.98,0,g2name,verticalalignment="center",horizontalalignment="right",size="smaller",color="w")


        def color_for_frac(f):
            # Blend g1color and g2color according to f (convex linear combination):
            # 0 returns g1color, 1 returns g2color)
            ret=np.array(g1colo

r)*f+np.array(g2color)*(1-f)
        if(np.linalg.norm(ret)>1):          # If the resulting rgb color is too bright for text,
            ret=(ret/np.linalg.norm(ret))*1 # rescale its brightness to dark (but keep hue)
        return ret

    for i,tl in enumerate(plt.gca().get_yticklabels()):
        tl.set_color(color_for_frac(pd.concat((bottom_df,top_df),axis=0).iloc[i]))

    sns.despine(ax=ax,left=True)

#fig,ax = plt.subplots(figsize=(7,14))
#compare_word_use(d_contains,
#                   g1=d["sex"]=="m",      g2=d["sex"]=="f",
#                   g1name="male users",   g2name="female users",
#                   g1color=[0.5,0.5,1.0], g2color=[1.0,0.5,0.5],
#                   ax=ax)

Я не знаю, так ли это, потому что у меня не установлено что-то или что-то еще.

Какой самый простой код, который я могу извлечь по ссылке выше, чтобы получить этот график без ошибок?

[enter image description here] 1

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