Positioning annotations with plotnine¶
Drawing annotations with aes(label='colname')
and geom_text()
can be simple, but positioning them well can be more difficult!
In [24]:
Copied!
import pandas as pd
from plotnine import *
df = pd.DataFrame([
{ 'name': 'seashells', 'amount': 65, 'price': 14 },
{ 'name': 'sand', 'amount': 40, 'price': 34 },
{ 'name': 'barnacles', 'amount': 23, 'price': 77 }
])
df
import pandas as pd
from plotnine import *
df = pd.DataFrame([
{ 'name': 'seashells', 'amount': 65, 'price': 14 },
{ 'name': 'sand', 'amount': 40, 'price': 34 },
{ 'name': 'barnacles', 'amount': 23, 'price': 77 }
])
df
Out[24]:
name | amount | price | |
---|---|---|---|
0 | seashells | 65 | 14 |
1 | sand | 40 | 34 |
2 | barnacles | 23 | 77 |
The problem¶
By default, your text annotations are centered on the same points that they are annotating
In [25]:
Copied!
(
ggplot(df)
+ aes(x='amount', y='price', label='name')
+ geom_point()
+ geom_text()
+ ylim(0, 80)
+ xlim(0, 80)
)
(
ggplot(df)
+ aes(x='amount', y='price', label='name')
+ geom_point()
+ geom_text()
+ ylim(0, 80)
+ xlim(0, 80)
)
Out[25]:
<ggplot: (312216784)>
Moving labels above the points they're annotating¶
To push a label up, use nudge_y
. Note that the numbers aren't pixels, but relative to your axis. So if you're plotting large numbers – zero to a million for example – your nudge values will probably be very high.
In [26]:
Copied!
(
ggplot(df)
+ aes(x='amount', y='price', label='name')
+ geom_point()
+ geom_text(nudge_y=3)
+ ylim(0, 80)
+ xlim(0, 80)
)
(
ggplot(df)
+ aes(x='amount', y='price', label='name')
+ geom_point()
+ geom_text(nudge_y=3)
+ ylim(0, 80)
+ xlim(0, 80)
)
Out[26]:
<ggplot: (312254016)>
Moving labels next to the points they're annotating¶
To move a label to the left or right, you need to do two things: change the alignment, and then nudge to prevent overlap. This means passing ha='left'
or ha='right'
to your geom_text
, along with a nudge_x
that moves your text away from your point.
In [27]:
Copied!
(
ggplot(df)
+ aes(x='amount', y='price', label='name')
+ geom_point()
+ geom_text(ha='left', nudge_x=1)
+ ylim(0, 80)
+ xlim(0, 80)
)
(
ggplot(df)
+ aes(x='amount', y='price', label='name')
+ geom_point()
+ geom_text(ha='left', nudge_x=1)
+ ylim(0, 80)
+ xlim(0, 80)
)
Out[27]:
<ggplot: (312291250)>
In [ ]:
Copied!