条形图竞赛轴格式化使用Python

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

bar chart race axis formating using Python

问题

以下是您要求的翻译部分:

我在我的数据集中有三列。'初始条件','给定初始条件发生A的概率'和'给定初始条件发生B的概率'。我想要在Python中创建一个柱状图动画 gif,其中我可以显示柱状图的进展(代表A和B的概率)随着初始条件的变化。我尝试过这个,但x轴代表柱状图的值要么是0,要么是1。我无法将其格式化以显示两位小数。如果有人能帮助我,那将非常有帮助。这是数据样本。

这是我使用的代码。

import pandas as pd
import matplotlib.pyplot as plt
import bar_chart_race as bcr

# Load the data
data = pd.read_csv('data.csv')

# Set the index to the starting capital of A
data = data.set_index('A的初始资本')

# Create the animated bar chart race
bcr.bar_chart_race(
    df=data,
    filename='race.gif',
    orientation='h',
    sort='desc',
    n_bars=3,
    steps_per_period=10,
    interpolate_period=False,
    label_bars=True,
    bar_size=.95,
    period_length=500,
    figsize=(6, 3),
    dpi=144,
    title='比赛',
    writer='pillow'
)

plt.show()

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

I have three columns in my dataset. &#39;Initial condition&#39;, &#39;Probability of A occurring given initial condition&#39; and &#39;Probability of B occurring given initial condition&#39;. I want a bar chart race animation gif in Python where I can show the progression of the bars (representing Probability of A and B) with changing initial condition. I tried doing this but the x-axis representing the values of the bar is either 0 or 1. I am unable to format it so that it gets shown in two decimal places. Would be really helpful if anyone can assist me. Here is the data sample. 

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

Here is the code I used. 

    import pandas as pd
    import matplotlib.pyplot as plt
    import bar_chart_race as bcr

    # Load the data
    data = pd.read_csv(&#39;data.csv&#39;)

    # Set the index to the starting capital of A
    data = data.set_index(&#39;Initial captial of A&#39;)

    # Create the animated bar chart race
    bcr.bar_chart_race(
        df=data,
        filename=&#39;race.gif&#39;,
        orientation=&#39;h&#39;,
        sort=&#39;desc&#39;,
        n_bars=3,
        steps_per_period=10,
        interpolate_period=False,
        label_bars=True,
        bar_size=.95,
        period_length=500,
        figsize=(6, 3),
        dpi=144,
        title=&#39;Race&#39;,
        writer=&#39;pillow&#39;
    )

    plt.show()


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

</details>


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

从我理解的情况来看,你需要使用matplotlib包中的 `ax.set_xticks()` 手动设置 x 轴刻度。

以下是一个使用虚拟数据演示这个想法的代码片段:

```python
import pandas as pd
import matplotlib.pyplot as plt
import bar_chart_race as bcr
import numpy as np
# 加载数据
# data = pd.read_csv('data.csv')
N = 20
data = pd.DataFrame({'A的初始资本': np.arange(N),
                     '概率_A': np.linspace(0, 1, N),
                     '概率_B': np.linspace(1, 0, N)})
# 将索引设置为A的初始资本
data = data.set_index('A的初始资本')
print(data.head())

# 创建动态条形图竞赛
fig, ax = plt.subplots(1, 1, figsize=(8, 4), dpi=120, tight_layout=True)
bcr.bar_chart_race(
    df=data,
    filename='race.gif',
    orientation='h',
    sort='desc',
    n_bars=3,
    steps_per_period=1,
    interpolate_period=True,
    label_bars=True,
    bar_size=.95,
    period_length=1,
    dpi=144,
    fig=fig,
    title='竞赛',
    writer='pillow',
    fixed_max=True,
    fixed_order=['概率_A', '概率_B']
)
ax.set_xticks(np.linspace(0, 1, 10))
plt.show()

如果你有进一步的问题,请随时告诉我。最好的问候。

英文:

From what I understand, you have to set up manually the x-ticks using ax.set_xticks() from matplotlib package.

Here is a code snippet to show you the idea with dummy data:

import pandas as pd
import matplotlib.pyplot as plt
import bar_chart_race as bcr
import numpy as np
# Load the data
# data = pd.read_csv(&#39;data.csv&#39;)
N = 20
data = pd.DataFrame({&#39;Initial captial of A&#39;: np.arange(N),
                     &#39;Probability_A&#39;: np.linspace(0, 1, N),
                     &#39;Probability B&#39;: np.linspace(1, 0, N)})
# Set the index to the starting capital of A
data = data.set_index(&#39;Initial captial of A&#39;)
print(data.head())

# Create the animated bar chart race
fig, ax = plt.subplots(1, 1, figsize=(8, 4), dpi=120, tight_layout=True)
bcr.bar_chart_race(
    df=data,
    filename=&#39;race.gif&#39;,
    orientation=&#39;h&#39;,
    sort=&#39;desc&#39;,
    n_bars=3,
    steps_per_period=1,
    interpolate_period=True,
    label_bars=True,
    bar_size=.95,
    period_length=1,
    dpi=144,
    fig=fig,
    title=&#39;Race&#39;,
    writer=&#39;pillow&#39;,
    fixed_max=True,
    fixed_order=[&#39;Probability_A&#39;, &#39;Probability B&#39;]
)
ax.set_xticks(np.linspace(0, 1, 10))
plt.show()

Let me know if you have further questions.
Best regards.

答案2

得分: 0

以下是翻译好的部分:

  1. "The amount of decimal places for the bar labels is hard-coded to zero in the current version 0.1.0 of the package."

    • "当前包的版本0.1.0中,柱形标签的小数位数是硬编码为零。"
  2. "The latest version 0.2.0 of bar_chart_race is not available via PIP yet, but can be installed in other ways (see last answer):"

    • "bar_chart_race的最新版本0.2.0尚不可通过PIP获得,但可以通过其他方式进行安装(请参见最后的回答)。"
  3. "Terminal:"

    • "终端:"
  4. "pip uninstall bar_chart_race"

    • "pip卸载 bar_chart_race"
  5. "pip install git+https://github.com/dexplo/bar_chart_race"

    • "pip安装 git+https://github.com/dexplo/bar_chart_race"
  6. "With this latest version, you can add the keyword bar_texttemplate=&#39;{x:,.2f}&#39; to get two decimal places (but some other keywords like "label_bars" and "dpi" have to be removed)."

    • "使用这个最新版本,您可以添加关键字 bar_texttemplate=&#39;{x:,.2f}&#39; 以获得两位小数(但必须删除一些其他关键字,如“label_bars”和“dpi”)。"
  7. "Same goes for the xtick-labels via tick_template=&quot;{x:,.2f}&quot;:"

    • "对于xtick标签也是一样的,使用 tick_template=&quot;{x:,.2f}&quot;:"
  8. "import pandas as pd"

    • "导入 pandas as pd"
  9. "import matplotlib.pyplot as plt"

    • "导入 matplotlib.pyplot as plt"
  10. "import bar_chart_race as bcr"

    • "导入 bar_chart_race as bcr"
  11. "import numpy as np"

    • "导入 numpy as np"
  12. "N = 20"

    • "N = 20"
  13. "data = pd.DataFrame(...)"

    • "data = pd.DataFrame(...)"
  14. "Set the index to the starting capital of A"

    • "将索引设置为A的初始资本"
  15. "Create the animated bar chart race"

    • "创建动态条形图赛"
  16. "bcr.bar_chart_race(...)"

    • "bcr.bar_chart_race(...)"
  17. "1: https://github.com/dexplo/bar_chart_race/issues/26"

  18. "2: https://i.stack.imgur.com/SXoJb.gif"

英文:

I will post this as an answer, as it might get lost as a comment:

The amount of decimal places for the bar labels is hard-coded to zero in the current version 0.1.0 of the package. The latest version 0.2.0 of bar_chart_race is not available via PIP yet, but can be installed in other ways (see last answer):

Terminal:

pip uninstall bar_chart_race
pip install git+https://github.com/dexplo/bar_chart_race

With this latest version, you can add the keyword bar_texttemplate=&#39;{x:,.2f}&#39; to get two decimal places (but some other keywords like "label_bars" and "dpi" have to be removed). Same goes for the xtick-labels via tick_template=&quot;{x:,.2f}&quot;:

条形图竞赛轴格式化使用Python

import pandas as pd
import matplotlib.pyplot as plt
import bar_chart_race as bcr
import numpy as np

N = 20
data = pd.DataFrame(
    {
        &quot;Initial captial of A&quot;: np.arange(N),
        &quot;Probability_A&quot;: np.linspace(0, 1, N),
        &quot;Probability B&quot;: np.linspace(1, 0, N),
    }
)
# Set the index to the starting capital of A
data = data.set_index(&quot;Initial captial of A&quot;)

# Create the animated bar chart race
bcr.bar_chart_race(
    df=data,
    filename=&quot;race.gif&quot;,
    interpolate_period=True,
    writer=&quot;pillow&quot;,
    fixed_max=True,
    bar_texttemplate=&quot;{x:,.2f}&quot;,
    tick_template=&quot;{x:,.2f}&quot;,
)

huangapple
  • 本文由 发表于 2023年4月4日 03:48:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923265.html
匿名

发表评论

匿名网友

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

确定