【问题标题】:Displace pyplot bars along x-axis that has string ticks沿具有字符串刻度的 x 轴替换 pyplot 条
【发布时间】:2021-05-05 22:50:34
【问题描述】:

因此,在此图表上: 我希望“Margem EBITDA”栏与其他两个相互重叠的栏并排。我做了一些研究,大多数答案都建议用数字代替它,但由于我的 x-ticks 是字符串,我必须用一个完整的解决方法来绘制数字然后替换刻度,我真的不想这样做。代码如下:

meses=['Fevereiro/21', 'Março/21', 'Abril/21']
faturamentor=[498899.40, 623122.74, 653200.18]
faturamento=[499, 623, 653]
gasto=[65, 130, 188]
margem=[84.7, 76.6, 69.5]

locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')

seaborn.set()
seaborn.set_style("white")

plt.rcParams["figure.figsize"] = (19,10)
plt.rcParams["font.family"] = "Calibri"
plt.rc('font', size=14) 
plt.rc('axes', labelsize=20)
plt.rc('xtick', labelsize=15)
plt.rc('ytick', labelsize=15)
plt.rc('legend', fontsize=15)

ax = plt.subplot(111)
ax.bar(meses, faturamento, width=0.3, color='#434343', align='center', label='Faturamento líquido')
ax.bar(meses, gasto, width=0.3, color='#999999', align='center', label='Gasto em anúncios')
ax.grid(axis='y')
ax.set_ylabel('Valor (milhares de reais)')

for i in range(len(faturamento)):
    plt.annotate(xy=(i, faturamento[i]+10), text=f'R${faturamentor[i]:n}', ha='center', va='center', color='#434343')

plt.legend()
plt.xlabel('Mês')
plt.ylim(0, faturamento[-1]+(0.1*faturamento[-1]))

ax2 = ax.twinx()
ax2.set_ylabel('Margem EBITDA (%)')
ax2.bar(meses, margem, label="Margem EBITDA", color='#cccccc', width=0.1)
ax2.tick_params(axis='y', labelcolor='k')
ax2.set_ylim(20, 92)
ax2.set_yticks([20, 30, 40, 50, 60, 70, 80, 90])

plt.legend()
fig1 = plt.gcf()
plt.show()

感谢您的帮助! 编辑:当我们这样做的时候,我怎样才能让两个轴的标签出现在同一个盒子上?

【问题讨论】:

    标签: python python-3.x matplotlib graph


    【解决方案1】:

    您可以使用np.linspace 在条上分配可用空间。使用ax.get_legend_handles_labels(),您可以提取图例信息,并使用组合信息创建新图例:

    from matplotlib import pyplot as plt
    import numpy as np
    import seaborn
    
    meses = ['Fevereiro/21', 'Março/21', 'Abril/21']
    faturamentor = [498899.40, 623122.74, 653200.18]
    faturamento = [499, 623, 653]
    gasto = [65, 130, 188]
    margem = [84.7, 76.6, 69.5]
    
    seaborn.set()
    seaborn.set_style("white")
    
    plt.rcParams["figure.figsize"] = (19, 10)
    plt.rcParams["font.family"] = "Calibri"
    plt.rc('font', size=14)
    plt.rc('axes', labelsize=20)
    plt.rc('xtick', labelsize=15)
    plt.rc('ytick', labelsize=15)
    plt.rc('legend', fontsize=15)
    
    num_meses = len(meses)
    num_bars = 3
    tot_width = .8
    dodge = np.linspace(-tot_width / 2, tot_width / 2, num_bars + 1)
    width = dodge[1] - dodge[0]
    
    ax = plt.subplot(111)
    ax.set_xticks(np.arange(num_meses))
    ax.set_xticklabels(meses)
    ax.bar(np.arange(num_meses) + dodge[0], faturamento, width=width,
           color='#434343', align='edge', label='Faturamento líquido')
    ax.bar(np.arange(num_meses) + dodge[1], gasto, width=width,
           color='#999999', align='edge', label='Gasto em anúncios')
    ax.grid(axis='y')
    ax.set_ylabel('Valor (milhares de reais)')
    
    for xpos, faturamento_i in zip(np.arange(num_meses) + dodge[0], faturamento):
        ax.annotate(xy=(xpos+width/2, faturamento_i), text=f'R${faturamento_i:n}\n', ha='center', va='center', color='#434343')
    
    ax.set_xlabel('Mês')
    ax.set_ylim(0, faturamento[-1] + (0.1 * faturamento[-1]))
    
    ax2 = ax.twinx()
    ax2.set_ylabel('Margem EBITDA (%)')
    ax2.bar(np.arange(num_meses) + dodge[2], margem, label="Margem EBITDA", color='#cccccc', width=width, align='edge')
    ax2.tick_params(axis='y', labelcolor='k')
    ax2.set_ylim(20, 92)
    ax2.set_yticks([20, 30, 40, 50, 60, 70, 80, 90])
    
    handles1, labels1 = ax.get_legend_handles_labels()
    handles2, labels2 = ax2.get_legend_handles_labels()
    ax.legend(handles=handles1 + handles2, labels=labels1 + labels2)
    
    plt.show()
    

    【讨论】:

    • 非常好的+1,但我认为他们仍然希望其他人堆叠,就像ax2.bar(np.arange(len(meses))+0.25, margem, label='Margem EBITDA', color='#cccccc', width=0.1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2018-04-13
    • 2018-06-11
    • 2019-09-06
    • 2017-09-26
    • 2020-05-29
    • 2016-12-30
    相关资源
    最近更新 更多