【问题标题】:Matplotlib bar chart: how to change names on axis xMatplotlib 条形图:如何更改轴 x 上的名称
【发布时间】:2021-05-07 17:00:15
【问题描述】:

我想创建一个条形图,其中包含 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.T,我做了一些更改。

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'])

图表现在看起来不错:)

【问题讨论】:

  • 您最初的问题在 kaggle 之外无法重现(matplotlib 3.3.3、Python 3.8、pandas 1.1.4)。作为一种解决方法,您可以在之后使用您的列 S 重新定义 xtick 标签:stackoverflow.com/a/30280076/8881141
  • 谢谢 - 我尝试使用它,但它不起作用。显示修改后外观的图片如下
  • 这不是链接线程所暗示的。它说使用ax = df_to_plot.plot.bar(y=['P(S)', 'P(S|X)'], alpha=0.7,... 将其绘制在索引上,然后使用ax.set_xticklabels(df_to_plot["S"]) 替换索引标签。这样做的结果是什么?无论如何仍然是奇怪的行为。
  • 谢谢!它现在可以正常工作

标签: python matplotlib data-science bar-chart kaggle


【解决方案1】:

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

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()

【讨论】:

  • 嗯,很有趣。我再次将我的代码放入一个新的 Kaggle 笔记本(我忘了提到我在 Kaggle 笔记本中工作(相当于 Jupyter))并收到了我之前得到的东西。但很高兴看到你的结果很好!
猜你喜欢
  • 2021-09-14
  • 2021-06-28
  • 2013-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
相关资源
最近更新 更多