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

Matplotlib:如何从列表中给定xticks值

  •  0
  • SaadH  · 技术社区  · 6 年前

    我有以下代码:

    import matplotlib.pyplot as plt
    import numpy as np
    
    xticks = ['A','B','C']
    Scores = np.array([[5,7],[4,6],[8,3]])
    colors = ['red','blue']
    fig, ax = plt.subplots()
    ax.hist(Scores,bins=3,density=True,histtype='bar',color=colors)
    plt.show()
    

    这将提供以下输出:

    histogram of code

    我有两个问题:

    1. 如何使条形图的高度表示中的值 Scores

    2. 如何跨x轴从指定值 xticks

    3 回复  |  直到 5 年前
        1
  •  3
  •   ImportanceOfBeingErnest    6 年前

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    
    xticks = ['A','B','C']
    Scores = np.array([[5,7],[4,6],[8,3]])
    colors = ['red','blue']
    names = ["Cat", "Dog"]
    fig, ax = plt.subplots()
    pd.DataFrame(Scores, index=xticks, columns=names).plot.bar(color=colors, ax=ax)
    plt.show()
    

    enter image description here

    如果单独使用matplotlib,会稍微复杂一些,因为每个列都需要单独绘制,

    import matplotlib.pyplot as plt
    import numpy as np
    
    xticks = ['A','B','C']
    Scores = np.array([[5,7],[4,6],[8,3]])
    colors = ['red','blue']
    names = ["Cat", "Dog"]
    
    fig, ax = plt.subplots()
    
    x = np.arange(len(Scores))
    ax.bar(x-0.2, Scores[:,0], color=colors[0], width=0.4, label=names[0])
    ax.bar(x+0.2, Scores[:,1], color=colors[1], width=0.4, label=names[1])
    ax.set(xticks=x, xticklabels=xticks)
    ax.legend()
    plt.show()
    

    enter image description here

        2
  •  1
  •   Polkaguy6000    6 年前

    import matplotlib.pyplot as plt
    import numpy as np
    
    xticks = ['A','B','C']
    Scores = np.array([[5,7],[4,6],[8,3]])
    colors = ['red','blue']
    fig, ax = plt.subplots()
    
    # Width of bars
    w=.2
    
    # Plot both separately
    ax.bar([1,2,3],Scores[:,0],width=w,color=colors[0])
    ax.bar(np.add([1,2,3],w),Scores[:,1],width=w,color=colors[1])
    
    # Assumes you want ticks in the middle
    ax.set_xticks(ticks=np.add([1,2,3],w/2))
    
    ax.set_xticklabels(xticks)
    plt.show()
    
        3
  •  0
  •   Reedinationer    6 年前

    plt.xticks(range(0, 6), ('A', 'A', 'B', 'B', 'C', 'C'))

    推荐文章