Wrap legend text in ggplot2
Ok, given your edits, you probably wanted this:
library(scales)
i + guides(colour = guide_legend(nrow = 2))
But you may find that you still want to employ the text wrapping technique as well, to get it to fit.
How can I make legend text wrap?
Adding white-space: normal;
to the legend works fine except in IE7 and IE6. Please see this jsfiddle demo
After playing around a bit with the CSS, I got it work on IE7, IE8, IE9, FF3-4, and Chrome11 by adding a <span>
inside the <legend>
with the below CSS:
legend {
white-space: normal;
width: 100%;
*margin-left: -7px;
}
legend span {
display:block;
width: 100%;
}
Please have a look at this jsfiddle
matplotlib - wrap text in legend
You can use textwrap.wrap
in order to adjust your legend entries (found in this answer), then update them in the call to ax.legend()
.
import random
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from textwrap import wrap
sns.set_style('darkgrid')
df = pd.DataFrame({'Year': [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016],
'One legend label': [random.randint(1,15) for _ in range(10)],
'A much longer, much more inconvenient, annoying legend label': [random.randint(1, 15) for _ in range(10)]})
random.seed(22)
fig, ax = plt.subplots()
labels = [ '\n'.join(wrap(l, 20)) for l in df.columns]
df.plot.line(x='Year', ax=ax,)
ax.legend(labels, bbox_to_anchor=(1, 0.5))
plt.subplots_adjust(left=0.1, right = 0.7)
plt.show()
Which gives:
Update: As pointed out in the comments, the documentation says textwrap.fill()
is shorthand for '\n'.join(wrap(text, ...))
. Therefore you can instead use:
from textwrap import fill
labels = [fill(l, 20) for l in df.columns]
Getting LEGEND tags to wrap text properly
Is it a requirement to use the <span>
tag? I was able to get this working in Firefox 3.6.2 using a <div>
tag and removing the dislay: block;
element (as it is not needed in that case) as follows.
<legend>
<div style="border: 1px solid blue; width: 250px;">
This text should wrap if it gets longer than 250px in width
</div>
</legend>
It is at least an alternative unless you must use the <span>
tag.
Related Topics
How to Ellipse a Clipping Mask on the Bottom Only
CSS Import or <Link Rel...> with "Media" Attribute
Enforce a "Min-Margin" for a Fluid Layout
Stray Vertical Line Above 965 Pixels with Border Radius in Safari
Fill Svg Element with With a Background-Image with an Offset
HTML and CSS: Using Background Image as a Clickable Link
Remove Value Attribute of Input Element Using CSS Only
Float Multiple Fixed-Width/Varible-Height Boxes into 2 Columns
3 Column Layout (Fixed, Fluid, Fixed) with Minimum Width
Best JSON-Ld Practices: Using Multiple <Script> Elements
Strip All HTML Tags Except Links
Using 100Vw and Vh Creates Extra Space Beyond Viewport Size. How to Get Rid of It