【问题标题】:Barchart with vertical labels in python/matplotlibpython/matplotlib 中带有垂直标签的条形图
【发布时间】:2010-11-16 07:20:59
【问题描述】:

我正在使用 matplotlib 生成(垂直)条形图。问题是我的标签很长。有什么方法可以垂直显示它们,无论是在栏中还是在其上方或下方?

【问题讨论】:

    标签: python charts matplotlib bar-chart


    【解决方案1】:

    你的意思是这样的:

    >>> from matplotlib import *
    >>> plot(xrange(10))
    >>> yticks(xrange(10), rotation='vertical')
    

    ?

    一般来说,要在 matplotlib 中以垂直方向显示任何文本,您可以添加关键字rotation='vertical'

    更多选项可以查看help(matplotlib.pyplot.text)

    yticks 函数在 y 轴上绘制刻度;我不确定您最初是指 this 还是 ylabel 函数,但过程总是相同的,您必须添加 rotation='vertical'

    也许您还可以找到有用的选项“verticalalignment”和“horizo​​ntalalignment”,它们允许您定义如何相对于刻度或其他元素对齐文本。

    【讨论】:

    • 请注意,我没有使用 plot();但是酒吧()。但 rotation='vertical' 似乎是关键。但是,这仍然不会在条形图中绘制刻度。
    • 你是指xy轴的刻度吗?看看网格函数。例如 grid(ls='', marker='v') 。 grid() 控制网格在 xy 轴上的绘制;使用标记选项定义刻度标记的阶梯,使用 ls='' 得到不可见的网格。
    • 除非有更好的答案出现,否则你会得到赏金,保证。不过,我将在 2009 年 8 月 9 日之前无法访问互联网 :(
    • 谢谢!!但是,对于这样的答案,也许500分太多了,这并不难。所以如果你,你可以把积分留到下次:)
    • 如何对现有的自动生成的刻度标签执行此操作?
    【解决方案2】:

    在 Jupyter Notebook 中你可能会使用类似这样的东西

    %matplotlib inline
    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.xticks(rotation='vertical')
    plt.plot(np.random.randn(100).cumsum())
    

    或者你可以使用:

    plt.xticks(rotation=90)
    

    【讨论】:

    • 我认为这是与 plt.bar() 一起使用的那个,这是 OP 所要求的。
    【解决方案3】:

    请查看此链接: https://python-graph-gallery.com/7-custom-barplot-layout/

    import matplotlib.pyplot as plt
    
    heights = [10, 20, 15]
    bars = ['A_long', 'B_long', 'C_long']
    y_pos = range(len(bars))
    plt.bar(y_pos, heights)
    # Rotation of the bars names
    plt.xticks(y_pos, bars, rotation=90)
    

    结果会是这样

    希望对您有所帮助。

    【讨论】:

    • 有没有办法把标签放在一个角度,比如对角线。
    • 嗨,Nguai al,您可以简单地将最后一行中的“旋转”参数更改为您喜欢的任何角度。例如,plt.xticks(y_pos, bar, rotation=45),会给你一个 45 度的 x 标签。
    【解决方案4】:

    我建议查看the matplotlib gallery。至少有两个例子似乎是相关的:

    【讨论】:

      猜你喜欢
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      相关资源
      最近更新 更多