import pandas as pd
from plotnine import *
df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6],
'sex':['male', 'female', 'male', 'male', 'female', 'female'],
'UA': [420, 300, 320, 500, 390, 320]})
# df为:
id sex UA
0 1 male 420
1 2 female 300
2 3 male 320
3 4 male 500
4 5 female 390
5 6 female 320
"""绘制柱状图"""
print( ggplot(df.groupby(['sex'])['UA']\
.agg(['mean']).reset_index())
+ geom_col( aes(y='mean', x='sex'))
)
![](https://i-blog.csdnimg.cn/blog_migrate/d5f03c98e71f1c0c553ce0e361fe3ac0.png)
1、添加文本
print( ggplot(df.groupby(['sex'])['UA']\
.agg(['mean']).reset_index())
+ geom_col( aes(y='mean', x='sex'))
+ annotate("text",
x = 1.5, y = 430,
label = "*****")
)
![](https://i-blog.csdnimg.cn/blog_migrate/939f0f73e6fc79f6ffc2f9716427e3de.png)
2、添加线段
print( ggplot(df.groupby(['sex'])['UA']\
.agg(['mean']).reset_index())
+ geom_col( aes(y='mean', x='sex'))
+ annotate("segment",
x = 1, y= 420,
xend = 2, yend = 420)
)
![](https://i-blog.csdnimg.cn/blog_migrate/3d96e3f19037777f0e462c350c7c56ae.png)
3、添加矩形阴影
print( ggplot(df.groupby(['sex'])['UA']\
.agg(['mean']).reset_index())
+ geom_col( aes(y='mean', x='sex'))
+ annotate("rect",
xmin = 1, xmax = 2,
ymin = 300, ymax = 430,
alpha = 0.7,
fill = "skyblue")
)
![](https://i-blog.csdnimg.cn/blog_migrate/76d54a707a52fe00b2daa45dc977c73f.png)