Skip to content

Instantly share code, notes, and snippets.

@joseph-allen
Created December 4, 2018 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joseph-allen/2de3244213295b885f817a48117d8bb4 to your computer and use it in GitHub Desktop.
Save joseph-allen/2de3244213295b885f817a48117d8bb4 to your computer and use it in GitHub Desktop.
plots multiple y axes on one graph
def plot_multi(data, cols=None, spacing=.1, **kwargs):
from pandas import plotting
# Get default color style from pandas - can be changed to any other color list
if cols is None: cols = data.columns
if len(cols) == 0: return
colors = getattr(getattr(plotting, '_style'), '_get_standard_colors')(num_colors=len(cols))
# First axis
ax = data.loc[:, cols[0]].plot(label=cols[0], color=colors[0], **kwargs)
ax.set_ylabel(ylabel=cols[0])
lines, labels = ax.get_legend_handles_labels()
for n in range(1, len(cols)):
# Multiple y-axes
ax_new = ax.twinx()
ax_new.spines['right'].set_position(('axes', 1 + spacing * (n - 1)))
data.loc[:, cols[n]].plot(ax=ax_new, label=cols[n], color=colors[n % len(colors)])
# set x and y values
ax_new.set_ylabel(ylabel=cols[n])
# Proper legend position
line, label = ax_new.get_legend_handles_labels()
lines += line
labels += label
ax.legend(lines, labels, loc=0)
return ax
# plot all columns
# format data if you need
data = pd.DataFrame(dict(
Col1=reverse_load_df['Col1'],
Col2=reverse_load_df['Col2']
))
plot_multi(df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment