首页 > 解决方案 > Matplotlib 条形图:如何更改轴 x 上的名称

问题描述

我想创建一个条形图,其中包含 2 列数据框的条形图。

from matplotlib import pyplot as plt
import pandas as pd

s = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
p_s = [0.05, 0.15, 0.20, 0.30, 0.20, 0.10]
p_s_x = [0.06005163309361129, 0.4378503494734475,0.3489460783665687,0.1404287057633398,0.012362455732360653,0.00036077757067209113]

df_to_plot = pd.DataFrame(data={"P(S)": p_s,
                                "P(S|X)": p_s_x,
                                "S": s})

df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                    alpha=0.7,
                    color=['red', 'green'],
                    figsize=(8,5))

这个数据框在这里。

在此处输入图像描述.

我生成的条形图

df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                   alpha=0.7,
                   color=['red', 'green'],
                   figsize=(8,5));

看起来

在此处输入图像描述

我想将 0,1 ,..., 5 替换为 0.1, ..., 0.6 (这是我的列 S),所以我设置了 x。

df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                    x='S',
                    alpha=0.7,
                    color=['red', 'green'],
                    figsize=(8,5));

结果如下。 在此处输入图像描述

我不知道如何纠正它。我曾经使用参数use_index,xticks,但它们无法工作。

你能看看它并提出建议吗?谢谢!

编辑 感谢@Mr.TI 做了一些更改。

ax = df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                         alpha=0.7,
                         color=['red', 'green'],
                         figsize=(8,5));
                         ax.set_xticklabels(df_to_plot['S'])

图表现在看起来不错:) 在此处输入图像描述

标签: pythonmatplotlibdata-sciencebar-chartkaggle

解决方案


我正在写一个答案,因为由于声誉低,我无法发表评论。给定您的代码,它会使用 matplotlib 3.3.4 版创建预期的输出。 结果图片

from matplotlib import pyplot as plt
import pandas as pd


if __name__ == '__main__':
    s = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
    p_s = [0.05, 0.15, 0.20, 0.30, 0.20, 0.10]
    p_s_x = [0.06005163309361129, 0.4378503494734475,0.3489460783665687,0.1404287057633398,0.012362455732360653,0.00036077757067209113]
    
    df_to_plot = pd.DataFrame(data={"P(S)": p_s,
                                    "P(S|X)": p_s_x,
                                    "S": s})
    
    df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'],
                    x='S',
                    alpha=0.7,
                    color=['red', 'green'],
                    figsize=(8,5))
    plt.show()

推荐阅读