【问题标题】:Matplotlib - place pie charts in a gridMatplotlib - 在网格中放置饼图
【发布时间】:2016-06-06 09:31:32
【问题描述】:

我正在尝试将饼图组织在一个网格中,在左侧的另一列中,我在特定行的饼图上写了一些相关数据。现在我的代码是:

data = [[0.3,0.3,0.3,0.1],[0.2,0.2,0.2,0.4],[0.1,0.1,0.4,0.4]]


def main():
    createPieCharts(data)
    return 0


def createPieCharts(data,piecharts_fname="piecharts"):
    """ """
    import datetime
    from matplotlib.backends.backend_pdf import PdfPages
    import matplotlib.pyplot as plt
    areas = ['Arava','Lotz','Paran','Ramon']
    thresholds = [0.0,0.01,0.02]
    num_columns = len(areas)
    num_rows    = len(thresholds)
    with PdfPages(piecharts_fname+'.pdf') as pdf:
        fig, ax = plt.subplots(num_rows,num_columns)
#            fig.suptitle('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
        labels = ['Frogs', 'Hogs', 'Dogs', 'Logs']
        for i,threshold in enumerate(thresholds):
            fracs = data[i]
            for j,area in enumerate(areas):
                ax[i,j].set_title(area)
                ax[i,j].pie(fracs, labels=labels,
                            autopct='%1.1f%%', shadow=True, startangle=90)
                ax[i,j].set_aspect('equal')
        plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
        pdf.savefig(fig)
        plt.close()
        # Adding metadata for PDF file
        d = pdf.infodict()
        d['Title'] = 'Pie charts'
        d['CreationDate'] = datetime.datetime.today()

if __name__ == '__main__':
    main()

结果看起来像这样 虽然我希望它在左边有另一列,就像在这个例子中一样 -

什么是聪明的做法?

【问题讨论】:

    标签: python matplotlib charts pie-chart


    【解决方案1】:

    添加一个额外的列,并将您的文本放在那里。

    然后,您只需关闭左列 (ax.set_axis_off()) 中的坐标轴和刻度线,并使用ax.text 添加文本标签。

    请注意,您还需要为绘制饼图的其他轴的 j 索引添加 1。

    这是脚本中的函数,已修改:

    def createPieCharts(data,piecharts_fname="piecharts"):
        """ """
        import datetime
        from matplotlib.backends.backend_pdf import PdfPages
        import matplotlib.pyplot as plt
        areas = ['Arava','Lotz','Paran','Ramon']
        thresholds = [0.0,0.01,0.02]
        num_columns = len(areas) + 1                                # Add extra column for text
        num_rows    = len(thresholds)
        with PdfPages(piecharts_fname+'.pdf') as pdf:
            fig, ax = plt.subplots(num_rows,num_columns)
    #            fig.suptitle('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
            labels = ['Frogs', 'Hogs', 'Dogs', 'Logs']
            for i,threshold in enumerate(thresholds):
                fracs = data[i]
                ax[i,0].set_axis_off()                                  # Turn off axes & ticks
                ax[i,0].text(0.5,0.5,threshold,ha='center',va='center') # Add text
                for j,area in enumerate(areas):
                    ax[i,j+1].set_title(area)                           # Add 1 to j index
                    ax[i,j+1].pie(fracs, labels=labels,                 # Add 1 to j index
                                autopct='%1.1f%%', shadow=True, startangle=90)
                    ax[i,j+1].set_aspect('equal')                       # Add 1 to j index
            plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
            pdf.savefig(fig)
            plt.close()
            # Adding metadata for PDF file
            d = pdf.infodict()
            d['Title'] = 'Pie charts'
            d['CreationDate'] = datetime.datetime.today()
    

    【讨论】:

      【解决方案2】:

      如果您对轴对象使用特殊函数 is_first_col 标记 y 轴并使用 is_last_row 标记 x 轴,这是可能的:

      def createPieCharts(data,piecharts_fname="piecharts"):
          """ """
          import datetime
          from matplotlib.backends.backend_pdf import PdfPages
          import matplotlib.pyplot as plt
          areas = ['Arava','Lotz','Paran','Ramon']
          thresholds = [0.0,0.01,0.02]
          num_columns = len(areas)
          num_rows    = len(thresholds)
          val = 0. # to y axis labels
          with PdfPages(piecharts_fname+'.pdf') as pdf:
              fig, ax = plt.subplots(num_rows,num_columns)
              labels = ['Frogs', 'Hogs', 'Dogs', 'Logs']
              for i,threshold in enumerate(thresholds):
                  fracs = data[i]
                  for j,area in enumerate(areas):
                      ax[i,j].set_title(area)
                      ax[i,j].pie(fracs, labels=labels,
                                  autopct='%1.1f%%', shadow=True, startangle=90)
                      ax[i,j].set_aspect('equal')
                      # label y axis
                      if ax[i,j].is_first_col():
                          ax[i,j].set_ylabel(str(val), fontsize = 9, rotation = 0)
                          val += .01
              plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
              pdf.savefig(fig)
              plt.close()
              # Adding metadata for PDF file
              d = pdf.infodict()
              d['Title'] = 'Pie charts'
              d['CreationDate'] = datetime.datetime.today()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-21
        • 2013-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-05
        相关资源
        最近更新 更多