【问题标题】:Matplotlib histogram label text crowdedMatplotlib 直方图标签文本拥挤
【发布时间】:2018-07-28 21:22:06
【问题描述】:

我在 matplotlib 中制作直方图,每个 bin 的文本标签相互重叠,如下所示:

我尝试按照another solution 旋转x轴上的标签

cuisine_hist = plt.hist(train.cuisine, bins=100)
cuisine_hist.set_xticklabels(rotation=45)
plt.show()

但我收到错误消息'tuple' object has no attribute 'set_xticklabels'。为什么?我该如何解决这个问题?或者,我怎样才能“转置”绘图以使标签位于垂直轴上?

【问题讨论】:

    标签: python matplotlib histogram


    【解决方案1】:

    给你。我在一个例子中将这两个答案混为一谈:

    # create figure and ax objects, it is a good practice to always start with this
    fig, ax = plt.subplots()
    
    # then plot histogram using axis
    # note that you can change orientation using keyword
    ax.hist(np.random.rand(100), bins=10, orientation="horizontal")
    
    # get_xticklabels() actually gets you an iterable, so you need to rotate each label
    for tick in ax.get_xticklabels():
        tick.set_rotation(45)
    

    它生成带有旋转 x 刻度和水平直方图的图形。

    【讨论】:

      【解决方案2】:

      plt.hist的返回值不是你用来运行函数set_xticklabels的:

      运行该函数的是matplotlib.axes._subplots.AxesSubplot,您可以从这里获得:

      fig, ax = plt.subplots(1, 1)
      cuisine_hist = ax.hist(train.cuisine, bins=100)
      ax.set_xticklabels(rotation=45)
      plt.show()
      

      来自 plt.hist 的“帮助”:

      Returns
      -------
      n : array or list of arrays
          The values of the histogram bins. See *normed* or *density*
      
      bins : array
          The edges of the bins. ...
      
      patches : list or list of lists
         ...
      

      【讨论】:

        【解决方案3】:

        This 可能会有所帮助,因为它与旋转标签有关。

        import matplotlib.pyplot as plt
        
        
        x = [1, 2, 3, 4]
        y = [1, 4, 9, 6]
        labels = ['Frogs', 'Hogs', 'Bogs', 'Slogs']
        
        plt.plot(x, y, 'ro')
        # You can specify a rotation for the tick labels in degrees or with keywords.
        plt.xticks(x, labels, rotation='vertical')
        # Pad margins so that markers don't get clipped by the axes
        plt.margins(0.2)
        # Tweak spacing to prevent clipping of tick-labels
        plt.subplots_adjust(bottom=0.15)
        plt.show()
        

        我觉得

        plt.xticks(x, labels, rotation='vertical')
        

        是这里的重要线。

        【讨论】:

          【解决方案4】:

          只要这条简单的线就可以解决问题

          plt.xticks(rotation=45)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-04-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-12-26
            • 1970-01-01
            • 2020-09-20
            相关资源
            最近更新 更多