making matplotlib graphs look like R by default?

后端 未结 8 1744
自闭症患者
自闭症患者 2021-01-29 23:02

Is there a way to make matplotlib behave identically to R, or almost like R, in terms of plotting defaults? For example R treats its axes pretty differently from

8条回答
  •  长情又很酷
    2021-01-29 23:37

    Edit 1 year later:

    With seaborn, the example below becomes:

    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn
    seaborn.set(style='ticks')
    # Data to be represented
    X = np.random.randn(256)
    
    # Actual plotting
    fig = plt.figure(figsize=(8,6), dpi=72, facecolor="white")
    axes = plt.subplot(111)
    heights, positions, patches = axes.hist(X, color='white')
    seaborn.despine(ax=axes, offset=10, trim=True)
    fig.tight_layout()
    plt.show()
    

    Pretty dang easy.

    Original post:

    This blog post is the best I've seen so far. http://messymind.net/making-matplotlib-look-like-ggplot/

    It doesn't focus on your standard R plots like you see in most of the "getting started"-type examples. Instead it tries to emulate the style of ggplot2, which seems to be nearly universally heralded as stylish and well-designed.

    To get the axis spines like you see the in bar plot, try to follow one of the first few examples here: http://www.loria.fr/~rougier/coding/gallery/

    Lastly, to get the axis tick marks pointing outward, you can edit your matplotlibrc files to say xtick.direction : out and ytick.direction : out.

    Combining these concepts together we get something like this:

    import numpy as np
    import matplotlib
    import matplotlib.pyplot as plt
    # Data to be represented
    X = np.random.randn(256)
    
    # Actual plotting
    fig = plt.figure(figsize=(8,6), dpi=72, facecolor="white")
    axes = plt.subplot(111)
    heights, positions, patches = axes.hist(X, color='white')
    
    axes.spines['right'].set_color('none')
    axes.spines['top'].set_color('none')
    axes.xaxis.set_ticks_position('bottom')
    
    # was: axes.spines['bottom'].set_position(('data',1.1*X.min()))
    axes.spines['bottom'].set_position(('axes', -0.05))
    axes.yaxis.set_ticks_position('left')
    axes.spines['left'].set_position(('axes', -0.05))
    
    axes.set_xlim([np.floor(positions.min()), np.ceil(positions.max())])
    axes.set_ylim([0,70])
    axes.xaxis.grid(False)
    axes.yaxis.grid(False)
    fig.tight_layout()
    plt.show()
    

    The position of the spines can be specified a number of ways. If you run the code above in IPython, you can then do axes.spines['bottom'].set_position? to see all of your options.

    R-style bar plot in python

    So yeah. It's not exactly trivial, but you can get close.

提交回复
热议问题