Matplotlib margins

后端 未结 1 1586
慢半拍i
慢半拍i 2020-12-22 09:07

Look at the chart below. In this chart, I want to draw to circle with the centre coordinates at (45, 0). But, as you see, bottom limit of chart is zero and half of my circle

相关标签:
1条回答
  • 2020-12-22 09:50

    In the question there is no circle, so my answer doesn't include any circle either.

    In order to have some space around the data in the plot, you can use ax.margins(y=ymargin), where ymargin is the percentage of space to add on each side of the data. I.e. if data goes from 0 to 1 and you add ymargin = 0.1 of margin, the ylimits will be (-0.1, 1.1). (This is independent on whether or not one limit would be zero or not.)

    Now, by default this does not work for a bar plot, as it would in the general case be undesireable to have the bars start somewhere in the air, as opposed to the bottom axis. This behaviour is steered using a flag called use_sticky_edges. We can set this flag to False to get back the behaviour of margins being applied to both ends of the axis. For taking effect, we need to call ax.autoscale_view afterwards.

    import matplotlib.pyplot as plt
    import numpy as np
    
    values = np.array([3.89, 3.76, 3.55, 3.28, 2.95, 2.72, 2.46, 2.28, 2.13, 2.03, 1.84, 
                       1.62, 1.48, 1.28, 1.12, 0.93, 0.79, 0.66, 0.58, 0.52, 0.56, 0.72, 
                       0.87, 1.09, 1.24, 1.37, 1.44, 1.35, 1.22, 1.13, 1.09, 1.02, 1.01, 
                       1.02, 1.05, 1.02, 1.01, 0.89, 0.78, 0.75, 0.67, 0.59, 0.66, 0.74, 
                       0.65, 0.60, 0.58, 0.50, 0.28, 0.36])
    
    fig, ax = plt.subplots()
    ax.bar(np.arange(values.shape[0]), values)
    
    ax.margins(y=0.3)
    ax.use_sticky_edges = False
    ax.autoscale_view(scaley=True)
    plt.show()
    

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