代码之家  ›  专栏  ›  技术社区  ›  Nicholas

巨蟒-天生的小提琴情节,不是我想做的

  •  1
  • Nicholas  · 技术社区  · 7 年前

    我在看一些例子,但是所有的东西都需要一个数据框架。

    如果我有以下数据帧:

    x = ["G","F","E","D","C","B"]
    y = [3,14,45,47,34,15]
    
    df = pd.DataFrame(
        {'Band': x,
         'Count': y,
        })
    

    我想用 Count 作为价值和 Band 作为步骤,我已经做到了:

    ax = sns.violinplot( y="Count", data=df)
    

    由此产生:

    enter image description here

    但是,我想拥有 Bands y axis ,然后 伯爵 每个坡度的凸起大小。你只需要用 continuous values Y轴 ?

    编辑:

    我想要的是:

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   ImportanceOfBeingErnest    7 年前

    小提琴图通常用于描述数据集的核密度。目前还不清楚离散数据集的核密度应该是多少,但您当然可以通过映射字母来假设离散情况是连续的 "B", "C", "D", ... 整数 0,1,2,... 然后画小提琴。

    import matplotlib.pyplot as plt
    import seaborn as sns
    
    x = ["G","F","E","D","C","B"]
    y = [3,14,45,47,34,15]
    
    data = []
    for i, yi in enumerate(y):
        data.extend([i]*yi)
    
    sns.violinplot(y=data)
    plt.yticks(range(len(x)), x)
    plt.show()
    

    enter image description here

    这给了一些关于字母分布的一般提示。然而,为了定量使用,人们可能宁愿绘制条形图。

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = ["G","F","E","D","C","B"]
    y = [3,14,45,47,34,15]
    
    plt.barh(np.arange(len(x)), y)
    plt.yticks(np.arange(len(x)), x)
    plt.show()
    

    enter image description here

    现在你当然可以用一种类似于小提琴的方式来设计条形图,或者叫它“圣诞树图”。

    import matplotlib.pyplot as plt
    import matplotlib.ticker as mticker
    import numpy as np
    
    x = ["G","F","E","D","C","B"]
    y = [3,14,45,47,34,15]
    
    plt.barh(np.arange(len(x)), y, height=1, color="C0")
    plt.barh(np.arange(len(x)), -np.array(y), height=1, color="C0")
    
    plt.yticks(np.arange(len(x)), x)
    
    # create strictly positive ticklabels
    posfmt = mticker.FuncFormatter(lambda x,_: "{:g}".format(np.abs(x)))
    plt.gca().get_xaxis().set_major_formatter(posfmt)
    plt.show()
    

    enter image description here