Skip to content

Instantly share code, notes, and snippets.

@parevalo
Created July 1, 2019 16:13
Show Gist options
  • Select an option

  • Save parevalo/2023a2ad7c4c6f036a91b2b73d842fdb to your computer and use it in GitHub Desktop.

Select an option

Save parevalo/2023a2ad7c4c6f036a91b2b73d842fdb to your computer and use it in GitHub Desktop.
Barplots of carbon emissions in Tg C (left) and Mg C /ha (right)
def simple_plotter(df, col_names, net_name, legend, fname):
periods = np.arange(2002, 2016, 2)
# Required, otherwise labels are shifted for some reason.
df['period'] = periods
ax1 = df.plot(x='period', y=col_names, kind='bar', stacked=True,
figsize = FIGSIZE, rot=0, use_index=False)
df.plot(x='period', y=net_name,kind='line', linestyle='-', marker='o',
color='black', ax=ax1, figsize=FIGSIZE, use_index=False, rot=0)
# Required to avoid figure being cut
plt.autoscale()
# Needed here otherwise gets overridden below
plt.legend(legend, bbox_to_anchor=(0.5 ,-0.3), ncol=2, loc='center', facecolor='white')
# Create secondary axis
ax2 = ax1.twinx()
ax2.grid(None)
# Get params from ax1 and set the same for ax2
ax2.set_ylim(ax1.get_ylim())
ax2_ticks = ax2.get_yticks() / TOT_AREA
ax2.set_yticks(ax2_ticks)
# RE set ylim after modifying the ticks
ax2_ylim = list(ax2.get_ylim())
ax2.set_ylim([i / TOT_AREA for i in ax2_ylim])
# Format ticks to be legible
ax1.get_yaxis().set_major_formatter(FORMATTER1)
ax2.get_yaxis().set_major_formatter(FORMATTER2)
# Set x ticks and labels
ax1.set_xticklabels(periods)
ax1.set_ylabel(YLABEL1)
ax2.set_ylabel(YLABEL2)
ax1.set_xlabel(XLABEL)
plt.axhline(color='black', linewidth=0.5)
plt.tight_layout()
plt.savefig(SAVE_PATH.joinpath(fname))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment