问题描述
俗话说:“授人以鱼,一日不饿。教人钓鱼,终生不饿。”
我这辈子都无法解释情节提要的文档。这根本不是对开发该软件包的优秀人员的批评 - 我真的很喜欢这个软件包,这就是我努力变得更好的原因,我真的很感激他们。
但我无法理解如何将文档应用到我的工作中。我必须花很长时间在谷歌上搜索一个有使用我想要实现的功能的工作示例的人,这可能非常耗时。
以在下图中插入箭头的任务为例。
文档在这里:
https://plotnine.readthedocs.io/en/stable/generated/plotnine.geoms.arrow.html
plotnine.geoms.arrow(angle=30,length=0.2,ends='last',type='open')
我尝试了以下组合:
p + geoms_arrow(angle=30,type='open')
p + geom_arrow(angle=30,type='open')
p + geoms.arrow(angle=30,type='open')
p + geom.arrow(angle=30,type='open')
p + geoms('arrow',angle=30,type='open')
p + geom('arrow',type='open')
p + arrow(angle=30,type='open')
与此相关,我也无法理解如何更改图例中的行数和列数。文档:
https://plotnine.readthedocs.io/en/stable/generated/plotnine.guides.guide_legend.html
plotnine.guides.guide_legend(**kwargs)
我尝试了以下各种组合:
p + guides(guide_legend(nrow=1))
但是什么也做不了。我能找到的实现 guide_legend
的唯一示例是:
http://www.danielrothenberg.com/blog/2017/Jul/declarative-visualization-in-python-update/
基于此我也尝试过:
+ guides(color=guide_legend(nrow=1))
我现在只是尝试一些随机的东西,没有任何成功。
你如何破译 plotnine 文档来完成上述 2 件事(即在下面的代码中将图例更改为 1 行 6 列,并插入一个箭头)。
注意:我真的想了解如何阅读文档,而不仅仅是解决这两个问题。这也将帮助我处理许多其他查询......
一些示例代码:
import pandas as pd
from plotnine import *
df = pd.DataFrame({})
df['cat1'] = ('1A','1A','1B','1C','1C')
df['cat2'] = ('2A','2B','2C','2D','2E','2F','2A','2F')
df['value'] = (0.8965,0.0579,0.0250,0.0119,0.0060,0.0027,0.7645,0.0989,0.0456,0.0319,0.0268,0.0322,0.5889,0.0947,0.0819,0.0772,0.0707,0.0866)
p = (ggplot(df,aes(x='cat1',y='value',fill='cat2'))
+ theme_light(8)
+ geom_bar(stat='identity',width=0.8,position='dodge',alpha=0.80)
+ theme(
legend_direction='horizontal',legend_position='bottom',)
+ guides(guide_legend(nrow=1))
)
p
解决方法
您错过了帮助页面中的一个重要部分:
这用于定义 geom_path 的箭头。
不太确定您将如何在绘图中使用它,因为 x 是一个因子,所以我在下面展示了箭头如何工作的示例。您还可以检查 geom_path 的 help page:
da = pd.DataFrame({'x':[1,2,3],'y':[4,5,6]})
p = (ggplot(da,aes(x='x',y='y'))
+ geom_path(arrow = arrow(angle=30,length=0.2,ends='last',type='open'))
)
p
对于图例,您需要指定要修改的图例,在您的情况下是:
p = (ggplot(df,aes(x='cat1',y='value',fill='cat2'))
+ theme_light(8)
+ geom_bar(stat='identity',width=0.8,position='dodge',alpha=0.80)
+ theme(
legend_direction='horizontal',legend_position='bottom',)
+ guides(fill=guide_legend(nrow=1))
)