Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a legend with only text

I have two plots that I want to make legends for, right now they look like this: enter image description here

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?

like image 328
Syd Avatar asked Jul 27 '15 19:07

Syd


3 Answers

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:

enter image description here

like image 85
Srivatsan Avatar answered Nov 08 '22 23:11

Srivatsan


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()

enter image description here

like image 36
tsveti_iko Avatar answered Nov 09 '22 01:11

tsveti_iko


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')

enter image description here

like image 1
user2660966 Avatar answered Nov 09 '22 01:11

user2660966