How to set axis ticks in multiples of pi (Python) (matplotlib)

前端 未结 6 1761
长发绾君心
长发绾君心 2020-12-08 04:37

I\'d like to make a plot in Python and have x range display ticks in multiples of pi.

Is there a good way to do this, not manually?

I\'m thinking of using

6条回答
  •  不知归路
    2020-12-08 05:37

    Solution for pi fractions:

    import numpy as np
    import matplotlib.pyplot as plt
    
    from matplotlib import rc
    rc('text', usetex=True) # Use LaTeX font
    
    import seaborn as sns
    sns.set(color_codes=True)
    
    1. Plot your function:
    fig, ax = plt.subplots(1)
    x = np.linspace(0, 2*np.pi, 1001)
    y = np.cos(x)
    ax.plot(x, y)
    plt.xlim(0, 2*np.pi)
    
    1. Modify the range of the grid so that it corresponds to the pi values:
    ax.set_xticks(np.arange(0, 2*np.pi+0.01, np.pi/4))
    
    1. Change axis labels:
    labels = ['$0$', r'$\pi/4$', r'$\pi/2$', r'$3\pi/4$', r'$\pi$',
              r'$5\pi/4$', r'$3\pi/2$', r'$7\pi/4$', r'$2\pi$']
    ax.set_xticklabels(labels)
    

提交回复
热议问题