Annotating a scatter plot in plotnine¶
First we'll drum up a sample dataset.
In [4]:
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[4]:
name | amount | price | |
---|---|---|---|
0 | seashells | 65 | 14 |
1 | sand | 40 | 34 |
2 | barnacles | 23 | 77 |
Annotate every point on a scatter plot using geom_text
¶
To annotate a scatter plot, you need to pass label='colname'
to your aes
. This tells geom_text
what the text label should be. You usually also use ha='left'
or ha='right'
to either left- or right-align the label, and nudge_x
or nudge_y
to give it a little extra space.
In [24]:
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[24]:
<ggplot: (314309614)>
In [ ]:
Copied!