如何用 python 绘制条形图?

How to plot bar chart with python?

我想用 2 classes 可视化条形图。 Class=0 蓝色,class=1 红色。

#here its my code
x = ['0','1']
real = df[df['fake'] == 0].count()
fake = df[df['fake'] == 1].count()
plt.bar(x, real, color='blue')
plt.bar(x, fake, color='red')
plt.title("Class Fake & Real")
plt.show() 

错误代码: ValueError:形状不匹配:无法将对象广播到单个形状

from matplotlib import pyplot as plt
x = ['0', '1']
real, fake = 5, 10
plt.bar(x[0], real, color='blue')
plt.bar(x[1], fake, color='red')
plt.title("Class Fake & Real")
plt.show()

您的错误可能来自 realfake 的错误类型。顺便说一句,为条形图配置不同的颜色,有更好的 solution.

您可以 seaborncountplot.

而不是使用 matplotlib 的条形图来绘制每个 class 的计数
plt.figure(figsize = (7,5))
sns.countplot(x = "fake", data = df, palette=["blue","red"])
plt.show() 

输出-