【问题标题】:Matplotlib Bar CustomizationMatplotlib 栏自定义
【发布时间】:2013-09-11 22:37:23
【问题描述】:

我的这部分代码生成图 (1) 中的条形图。我想知道如何修改它以生成图 (2) 中的条形图,这样更具可读性。

axs[4].set_xticks(range(N))
axs[4].set_xticklabels(words[inds],rotation = 'vertical')
axs[4].set_xlabel('word')
axs[4].set_yscale('log')
axs[4].set_ylabel('pagerank')
axs[4].set_title('Sorted PageRank biased by total word frequencies (c = '+str(c4)+')')
axs[4].bar(range(N),p4[inds],lw=2.5, align='center')

plt.subplots_adjust(hspace=.5)

plt.savefig('./figures/pageranks.pdf')

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以定义自己的函数,并使用plt.hlines 绘制水平线。如果您想在某个坐标轴上绘制它,只需将此坐标轴作为参数提供给ax 参数即可。

    import matplotlib.pyplot as plt
    import numpy as np
    
    def bar_tops(x, y, width=0.8, align='center', ax=None, **kwargs):
        x = np.array(x)
        y = np.array(y)
        if align == 'center':
            left = x - 0.5 * width
            right = x + 0.5 * width
        elif align == 'edge':
            left = x
            right = x + width
        if ax == None:
            ax = plt.gca()
        ax.hlines(y, left, right, **kwargs)
    

    示例用法:

    bar_tops(np.arange(10), np.sort(np.random.rand(10)), lw=2)
    plt.show()
    

    【讨论】:

      【解决方案2】:

      使用pylab.step 而不是 pylab.bar 可以让您更接近您想要的东西。它采用与bars 相同的参数,但绘制的是“步骤”而不是“条”。

      import pylab as p
      ax = p.gca()
      xbins = p.linspace(0.,10.,10)
      step_heights = [10, 9, 9, 9, 7, 6, 6, 5, 4, 3]
      ax.step(xbins, step_heights, linewidth=2.5, color="k",where="mid")
      ax.set_ylim(0.,11.)
      

      您可能还想查看更完整的 pylab.hist 文档。

      【讨论】:

      • 不可能使用step 方法水平绘制每个点。当使用pre/post 参数到where 时,步骤会被截断,而mid 每侧的两个步骤都会被截断
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-03
      • 2021-03-23
      • 1970-01-01
      • 2022-12-11
      • 2018-03-18
      相关资源
      最近更新 更多