Skip to content Skip to sidebar Skip to footer

Plotting And Color Coding Multiple Y-axes

This is my first attempt using Matplotlib and I am in need of some guidance. I am trying to generate plot with 4 y-axes, two on the left and two on the right with shared x axis. He

Solution 1:

How can I put the scale on max and min temp on a same scale?

Plot them in the same axes.

Also, how can I get rid of second y-axis with black color, scaled from 0 to 10?

Do not create that axes.

You want to plot four variables, two of them can go in the same subplot so you only need three subplots. But you are creating five of them?

Step by step

Keep in mind: different y scales <-> different subplots sharing x-axis.

Two variables with a common scale (left), two variables with independent scales (right).

  1. Create the primary subplot, let's call it ax1. Plot everything you want in it, in this case TMIN and TMAX as stated in your question.
  2. Create a twin subplot sharing x axis twinx(ax=ax1). Plot the third variable, say RAIN.
  3. Create another twin subplot twinx(ax=ax1). Plot the fourth variable 'RAD'.
  4. Adjust colors, labels, spine positions... to your heart's content.

Unsolicited advice: do not try to fix code you don't understand.

Solution 2:

Variation of the original plot showing how you can plot variables on multiple axes

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

url ='http://dropproxy.com/f/D34'

df= pd.read_csv(url, index_col=0, parse_dates=[0])

fig = plt.figure()

ax = fig.add_subplot(111) # Primary y
ax2 = ax.twinx() # Secondary y# Plot variables
ax.plot(df.index, df['TMAX'], color='red')
ax.plot(df.index, df['TMIN'], color='green')
ax2.plot(df.index, df['RAIN'], color='orange')
ax2.plot(df.index, df['RAD'],  color='yellow')

# Custom ylimit
ax.set_ylim(0,50)

# Custom x axis date formatsimport matplotlib.dates as mdates
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

Solution 3:

I modified @bishopo's suggestions to generate what I wanted, however, the plot still needs some tweaking with font sizes for axes label.

Here's what I have done so far.

import pandas as pd
%matplotlib inline

url ='http://dropproxy.com/f/D34'

df= pd.read_csv(url, index_col=0, parse_dates=[0])

from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt





if1:
    # Set the figure size, dpi, and background color
    fig = plt.figure(1, (16,9),dpi =300, facecolor = 'W',edgecolor ='k')


    # Update the tick label size to 12
    plt.rcParams.update({'font.size': 12})
    host = host_subplot(111, axes_class=AA.Axes)
    plt.subplots_adjust(right=0.75)

    par1 = host.twinx()
    par2 = host.twinx()
    par3 = host.twinx()

    offset = 60

    new_fixed_axis = par2.get_grid_helper().new_fixed_axis
    new_fixed_axis1 = host.get_grid_helper().new_fixed_axis
    par2.axis["right"] = new_fixed_axis(loc="right",
                                        axes=par2,
                                        offset=(offset, 0))
    par3.axis["left"] = new_fixed_axis1(loc="left",
                                        axes=par3,
                                        offset=(-offset, 0))

    par2.axis["right"].toggle(all=True)
    par3.axis["left"].toggle(all=True)
    par3.axis["right"].set_visible(False)


    # Set limit on both y-axes
    host.set_ylim(-30, 50)
    par3.set_ylim(-30,50)

    host.set_xlabel("Date")
    host.set_ylabel("Minimum Temperature ($^\circ$C)")
    par1.set_ylabel("Solar Radiation (W$m^{-2}$)")
    par2.set_ylabel("Rainfall (mm)")
    par3.set_ylabel('Maximum Temperature ($^\circ$C)')


    p1, = host.plot(df.index,df['TMIN'], 'm,')
    p2, = par1.plot(df.index, df.RAD, color ='#EF9600', linestyle ='--')
    p3, = par2.plot(df.index, df.RAIN, '#09BEEF')
    p4, = par3.plot(df.index, df['TMAX'], '#FF8284')

    par1.set_ylim(0, 36)
    par2.set_ylim(0, 360)

    host.legend()


    host.axis["left"].label.set_color(p1.get_color())
    par1.axis["right"].label.set_color(p2.get_color())
    par2.axis["right"].label.set_color(p3.get_color())
    par3.axis["left"].label.set_color(p4.get_color())



    tkw = dict(size=5, width=1.5)
    host.tick_params(axis='y', colors=p1.get_color(), **tkw)
    par1.tick_params(axis='y', colors=p2.get_color(), **tkw)
    par2.tick_params(axis='y', colors=p3.get_color(), **tkw)
    par3.tick_params(axis='y', colors=p4.get_color(), **tkw)
    host.tick_params(axis='x', **tkw)



    par1.axis["right"].label.set_fontsize(16)
    par2.axis["right"].label.set_fontsize(16)
    par3.axis["left"].label.set_fontsize(16)
    host.axis["bottom"].label.set_fontsize(16)
    host.axis["left"].label.set_fontsize(16)


    plt.figtext(.5,.92,'Weather Data', fontsize=22, ha='center')
    plt.draw()
    plt.show()

    fig.savefig("Test1.png") 

The output enter image description here

Post a Comment for "Plotting And Color Coding Multiple Y-axes"