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

如何在Python中绘制水平条形图的百分比标签?

  •  0
  • r2deeptube  · 技术社区  · 4 年前

    有人能帮我根据我的水平条形图的以下代码,以百分比绘制x轴标签吗?

    发现很难找到,因为我想要一个没有x轴标签和刻度的更简单的图表。

    [水平条形图][1]

    # Plot the figure size
    plt.figure(figsize= (8,6))
    
    # New variable and plot the question of the data frame in a normalized in a horizontal bar chat. 
    ax1 = df[q1].value_counts(normalize=True).sort_values().plot(kind="barh", color='#fd6a02', width=0.75, zorder=2)
    
    # Draw vague vertical axis lines and set lines to the back of the order
    vals = ax1.get_xticks()
    for tick in vals:
        ax1.axvline(x=tick, linestyle='dashed', alpha=0.4, color = '#d3d3d3', zorder=1)
        
    # Tot3als to produce a composition ratio
    total_percent = df[q1].value_counts(normalize=True) *100
    
    # Remove borders
    ax1.spines['right'].set_visible(False)
    ax1.spines['top'].set_visible(False)
    ax1.spines['left'].set_visible(False)
    ax1.spines['bottom'].set_visible(False)
    
    # Set the title of the graph inline with the Y axis labels. 
    ax1.set_title(q1, weight='bold', size=14, loc = 'left', pad=20, x = -0.16)
                 
    # ax.text(x,y,text,color)
    for i,val in enumerate(total):
        ax1.text(val - 1.5, i, str("{:.2%}".format(total_percent), color="w", fontsize=10, zorder=3)
    
    # Create axis labels
    plt.xlabel("Ratio of Responses", labelpad=20, weight='bold', size=12)
    

    每次我都会遇到EOF错误。有人能帮忙吗?

    0 回复  |  直到 4 年前
        1
  •  3
  •   r-beginners    4 年前

    它不是基于你的代码,但我会根据官方参考定制答案。 这一点是通过以下方式实现的 ax.text() ,这是一个循环过程。

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Fixing random state for reproducibility
    np.random.seed(19680801)
    
    plt.rcdefaults()
    fig, ax = plt.subplots()
    
    # Example data
    people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim')
    y_pos = np.arange(len(people))
    performance = 3 + 10 * np.random.rand(len(people))
    
    ax.barh(y_pos, performance,  align='center')
    ax.set_yticks(y_pos)
    ax.set_yticklabels(people)
    ax.invert_yaxis()  # labels read top-to-bottom
    ax.set_xlabel('Performance')
    ax.set_title('How fast do you want to go today?')
    
    # Totals to produce a composition ratio
    total = sum(performance)
    
    # ax.text(x,y,text,color)
    for i,val in enumerate(performance):
        ax.text(val - 1.5, i, str("{:.2%}".format(val/total)), color="w", fontsize=10)
    
    plt.show()
    

    enter image description here