plotnine:: 在 after_stat 中引用 facet_wrap 的参数是否有更好的方式?

huangapple go评论76阅读模式
英文:

plotnine:: is there a better way to refer args of facet_wrap in after_stat

问题

以下是您要的内容的翻译:

"I wants to show percentages for bar plots using plotnine with facet_wrap and stat = 'count'.
(Of course I can do it with preparation of values and stat = 'identity', but I want to avoid it.)
When I give the arg of facet_wrap to aes, I can refer it in after_stat.
But it needs to nullify the aes manually. it seems ridiculous.
Is there a better way to do it ?

Any help would be greatly appreciated. Below is an example;

from plotnine import *
from plotnine.data import mtcars
import pandas as pd

def prop_per_xcc(x, color, count):
    df = pd.DataFrame({'x': x, 'color': color, 'count': count})
    prop = df['count']/df.groupby(['x', 'color'])['count'].transform('sum')
    return prop

facet_num = mtcars.vs.nunique()

print(
    ggplot(mtcars, aes('factor(cyl)', fill='factor(am)')) + 
    geom_bar(position='fill') + 
    geom_text(aes(color = "factor(vs)",  # sets arg of facet wrap to refer in after_stat
                  label = after_stat('prop_per_xcc(x, color, count) * 100')),
              stat = 'count',
              position = position_fill(vjust = 0.5),
              format_string = '{:.1f}%',
              show_legend = False) +
    scale_color_manual(values = ["black"] * facet_num) +  # nullify the aes manually
    facet_wrap("vs")
)

plotnine:: 在 after_stat 中引用 facet_wrap 的参数是否有更好的方式?


[![enter image description here][1]][1]"

<details>
<summary>英文:</summary>

I wants to show percentages for bar plots using `plotnine` with `facet_wrap` and `stat = &#39;count&#39;`.  
(Of course I can do it with preparation of values and `stat = &#39;identity&#39;`, but I want to avoid it.)  
When I give the arg of `facet_wrap` to `aes`, I can refer it in `after_stat`.  
But it needs to nullify the `aes` manually. it seems ridiculous.  
Is there a better way to do it ? 

Any help would be greatly appreciated. Below is an example;

from plotnine import *
from plotnine.data import mtcars
import pandas as pd

def prop_per_xcc(x, color, count):
df = pd.DataFrame({'x': x, 'color': color, 'count': count})
prop = df['count']/df.groupby(['x', 'color'])['count'].transform('sum')
return prop

facet_num = mtcars.vs.nunique()

print(
ggplot(mtcars, aes('factor(cyl)', fill='factor(am)')) +
geom_bar(position='fill') +
geom_text(aes(color = "factor(vs)", # sets arg of facet wrap to refer in after_stat
label = after_stat('prop_per_xcc(x, color, count) * 100')),
stat = 'count',
position = position_fill(vjust = 0.5),
format_string = '{:.1f}%',
show_legend = False) +
scale_color_manual(values = ["black"] * facet_num) + # nullify the aes manually
facet_wrap("vs")
)

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/miJUW.png

</details>


# 答案1
**得分**: 1

您的想法是正确的,但您可能不了解正确的语法。您应该使用分阶段的审美评估。

```python
from plotnine import *
from plotnine.data import mtcars
import pandas as pd

def prop_per_xcc(x, label, count):
    df = pd.DataFrame({'x': x, 'label': label, 'count': count})
    prop = df['count']/df.groupby(['x', 'label'])['count'].transform('sum')
    return prop

facet_num = mtcars.vs.nunique()

print(
    ggplot(mtcars, aes('factor(cyl)', fill='factor(am)')) + 
    geom_bar(position='fill') + 
    geom_text(aes(label = stage(start="vs", after_stat='prop_per_xcc(x, label, count) * 100')),
              stat = 'count',
              position = position_fill(vjust = 0.5),
              format_string = '{:.1f}%',
              show_legend = False) +
    facet_wrap("vs")
)

plotnine:: 在 after_stat 中引用 facet_wrap 的参数是否有更好的方式?

它表示label映射到与分面相同的变量,然后在计算统计数据后由自定义函数进行精化。

英文:

You are thinking correctly, but just don't know about the right syntax. You should use staged aesthetic evaluation.

from plotnine import *
from plotnine.data import mtcars
import pandas as pd

def prop_per_xcc(x, label, count):
    df = pd.DataFrame({&#39;x&#39;: x, &#39;label&#39;: label, &#39;count&#39;: count})
    prop = df[&#39;count&#39;]/df.groupby([&#39;x&#39;, &#39;label&#39;])[&#39;count&#39;].transform(&#39;sum&#39;)
    return prop


facet_num = mtcars.vs.nunique()

print(
    ggplot(mtcars, aes(&#39;factor(cyl)&#39;, fill=&#39;factor(am)&#39;)) + 
    geom_bar(position=&#39;fill&#39;) + 
    geom_text(aes(label = stage(start=&quot;vs&quot;, after_stat=&#39;prop_per_xcc(x, label, count) * 100&#39;)),
              stat = &#39;count&#39;,
              position = position_fill(vjust = 0.5),
              format_string = &#39;{:.1f}%&#39;,
              show_legend = False) +
    facet_wrap(&quot;vs&quot;)
)

plotnine:: 在 after_stat 中引用 facet_wrap 的参数是否有更好的方式?

It says, the label is mapped to the same variable as the facets, then refined by the custom function after the statistics are calculated.

huangapple
  • 本文由 发表于 2023年2月24日 13:55:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553061.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定