I have two plots that I want to make legends for, right now they look like this:
I just want 'C3H8' and 'CO2' to be in the legend, excluding the blue boxes. Right now I am using the matplotlib.patches
module. Is there anything else I can use?
As mentioned by @PaulH, you just need to use either plt.text
or plt.annotate
for your case.
Example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10,100)
y = np.random.random(100)
y2 = np.random.random(100)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(x,y)
ax1.annotate("$C_{3}H_{8}$", xy=(0.9,0.9),xycoords='axes fraction',
fontsize=14)
ax2 = fig.add_subplot(212)
ax2.scatter(x,y2)
ax2.annotate("$CO_{2}$", xy=(0.9,0.9),xycoords='axes fraction',
fontsize=14)
fig.show()
Here the xy
parameter inside the annotate refer to the x and y
co-ordinates of your text. You can change them accordingly.
Produces:
You can just use the bbox text property in the pyplot annotation like this:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-1, 5), ylim=(-5, 3))
ax.annotate("$C_{3}H_{8}$",
xy=(0.86,0.9), xycoords='axes fraction',
textcoords='offset points',
size=14,
bbox=dict(boxstyle="round", fc=(1.0, 0.7, 0.7), ec="none"))
plt.show()
Here is another solution that looks slightly more like legend.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
def textonly(ax, txt, fontsize = 14, loc = 2, *args, **kwargs):
at = AnchoredText(txt,
prop=dict(size=fontsize),
frameon=True,
loc=loc)
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
ax.add_artist(at)
return at
at = textonly(plt.gca(), "Line 1\nLine 2", loc = 2)
at = textonly(plt.gca(), "Line 1\nLine 2", loc = 4, fontsize = 55)
plt.gcf().show()
raw_input('pause')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With