Elegantly changing the color of a plot frame in matplotlib

后端 未结 3 1234
长发绾君心
长发绾君心 2020-12-08 00:34

This is a kind of follow-up question to this post, where the coloring of axes, ticks and labels was discussed. I hope it is alright to open a new, extended question for this

相关标签:
3条回答
  • 2020-12-08 01:16

    Maybe it is a bit crude to answer my own question, but I would like to share what I could find so far. This version can color two subplots with axes [ax1, ax2] and [ax3, ax4] in two different colors. It is much shorter than the 16 lines I stated in my question above. It is inspired by Joe Kington's answer here and in twinx kills tick label color.

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Generate some data
    num = 200
    x = np.linspace(501, 1200, num)
    yellow_data, green_data , blue_data= np.random.random((3,num))
    green_data += np.linspace(0, 3, yellow_data.size)/2
    blue_data += np.linspace(0, 3, yellow_data.size)/2
    
    fig = plt.figure()
    plt.subplot(211) # Upper Plot
    ax1 = fig.add_subplot(211)
    ax1.fill_between(x, 0, yellow_data, color='yellow')
    ax2 = ax1.twinx()
    ax2.plot(x, green_data, 'green')
    plt.setp(plt.gca(), xticklabels=[])
    plt.subplot(212) # Lower Plot
    ax3 = fig.add_subplot(212)
    ax3.fill_between(x, 0, yellow_data, color='yellow')
    ax4 = ax3.twinx()
    ax4.plot(x, blue_data, 'blue')
    
    # Start coloring
    for ax, color in zip([ax1, ax2, ax3, ax4], ['green', 'green', 'blue', 'blue']):
        for ticks in ax.xaxis.get_ticklines() + ax.yaxis.get_ticklines():
            ticks.set_color(color)
        for pos in ['top', 'bottom', 'right', 'left']:
            ax.spines[pos].set_edgecolor(color)
    # End coloring
    
    plt.show()
    

    color_plots

    I marked this as accepted since it's the most compact solution that I could find so far. Still, I am open for other, maybe more elegant ways to solve it.

    0 讨论(0)
  • 2020-12-08 01:22

    Refactoring your code above:

    import matplotlib.pyplot as plt
    
    for ax, color in zip([ax1, ax2, ax3, ax4], ['green', 'green', 'blue', 'blue']):
        plt.setp(ax.spines.values(), color=color)
        plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color)
    
    0 讨论(0)
  • 2020-12-08 01:28

    Assuming you're using a reasonably up-to-date version of matplotlib (>= 1.0), perhaps try something like this:

    import matplotlib.pyplot as plt
    
    # Make the plot...
    fig, axes = plt.subplots(nrows=2)
    axes[0].plot(range(10), 'r-')
    axes[1].plot(range(10), 'bo-')
    
    # Set the borders to a given color...
    for ax in axes:
        ax.tick_params(color='green', labelcolor='green')
        for spine in ax.spines.values():
            spine.set_edgecolor('green')
    
    plt.show()
    

    enter image description here

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