import pandas as pd
from plotnine import*
df = pd.DataFrame({'id': [1, 2, 3, 4, 5, 6],
'sex':['male', 'female', 'male', 'male', 'female', 'female'],
'group': ['ctrl', 'treat1', 'treat1', 'treat2', 'ctrl', 'treat2'],
'UA': [420, 360, 320, 500, 390, 430]})
# df为:
id sex group UA
0 1 male ctrl 420
1 2 female treat1 360
2 3 male treat1 320
3 4 male treat2 500
4 5 female ctrl 390
5 6 female treat2 430
"""绘制柱状图"""
print( ggplot(df.groupby(['group','sex'])['UA']\
.agg(['mean']).reset_index())
+ geom_col( aes(y='mean', x='group', fill='sex'),
position='dodge')
)
修改图例标题
print( ggplot(df.groupby(['group','sex'])['UA']\
.agg(['mean']).reset_index())
+ geom_col( aes(y='mean', x='group', fill='sex'),
position='dodge')
+ labs(fill="Gender")
)
修改图例中各项的顺序
print( ggplot(df.groupby(['group','sex'])['UA']\
.agg(['mean']).reset_index())
+ geom_col( aes(y='mean', x='group', fill='sex'),
position='dodge')
+ scale_fill_discrete(limits = ['male', 'female'])
)
修改图例位置
print( ggplot(df.groupby(['group','sex'])['UA']\
.agg(['mean']).reset_index())
+ geom_col( aes(y='mean', x='group', fill='sex'),
position='dodge')
+ theme(legend_position= (0.4, 0.9))
)