Barchart with vertical labels in python/matplotlib

后端 未结 4 1022
栀梦
栀梦 2021-01-31 07:17

I\'m using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or

相关标签:
4条回答
  • 2021-01-31 07:31

    In Jupyter Notebook you might use something like this

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

    or you can use:

    plt.xticks(rotation=90)
    
    0 讨论(0)
  • 2021-01-31 07:35

    I would suggest looking at the matplotlib gallery. At least two of the examples seem to be relevant:

    • text_rotation.py for understanding how text layout works
    • barchart_demo2.py, an example of a bar chart with somewhat more complicated layout than the most basic example.
    0 讨论(0)
  • 2021-01-31 07:36

    Do you mean something like this:

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

    ?

    In general, to show any text in matplotlib with a vertical orientation, you can add the keyword rotation='vertical'.

    For further options, you can look at help(matplotlib.pyplot.text)

    The yticks function plots the ticks on the y axis; I am not sure whether you originally meant this or the ylabel function, but the procedure is alwasy the same, you have to add rotation='vertical'

    Maybe you can also find useful the options 'verticalalignment' and 'horizontalalignment', which allows you to define how to align the text with respect to the ticks or the other elements.

    0 讨论(0)
  • 2021-01-31 07:47

    Please check out this link: 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)
    

    The result will be like this

    Hopefully, it helps.

    0 讨论(0)
提交回复
热议问题