Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# https://stackoverflow.com/a/45925049/13369757
import matplotlib.pyplot as plt
import numpy as np
fig, host = plt.subplots(figsize=(12,10)) # (width, height) in inches
par1 = host.twinx()
par2 = host.twinx()
host.set_xlabel("Threshold")
host.set_ylabel("Overkill rate (%)")
par1.set_ylabel("Leakage rate (%)")
par2.set_ylabel("Unknown rate (%)")
x = [i for i in range(50,76)]
p1, = host.plot(x, overkill_list, color='red', label="Overkill rate", marker='o')
p2, = par1.plot(x, leakage_list, color='green', label="Leakage rate", marker='o')
p3, = par2.plot(x, unknown_list, color='blue', label="Unknown rate", marker='o')
lns = [p1, p2, p3]
host.legend(handles=lns, loc='lower right', bbox_to_anchor=(1, 0.1))
# right, left, top, bottom
par2.spines['right'].set_position(('outward', 60))
host.yaxis.label.set_color(p1.get_color())
par1.yaxis.label.set_color(p2.get_color())
par2.yaxis.label.set_color(p3.get_color())
par2.set_yticks(range(0,101,5))
for xx,y in zip(x,unknown_list):
label = "{:.1f}%".format(y)
plt.annotate(label, # this is the text
(xx,y), # these are the coordinates to position the label
textcoords="offset points", # how to position the text
xytext=(3,10), # distance from text to points (x,y)
ha='left') # horizontal alignment can be left, right or center
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
fig.tight_layout()
plt.savefig("pyplot_multiple_y-axis.pdf")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment