下面显示的是条形图的分类数据详细信息,该条形图来自特定的DataFrame
列,即coast
import seaborn as sns
import matplotlib as mpl
import matplotlib.pyplot as plt
IN: data['coast'].dtypes
OUT:
CategoricalDtype(categories=[0, 1], ordered=False)
IN: data['coast'].value_counts()
OUT:
0 21450
1 163
Name: coast, dtype: int64
下面所示的语法是用于获取条形图的已定义函数。
def code(c):
plt.rc('figure', figsize=(10, 5))
ax = c.value_counts().plot(kind='bar')
for value in ax:
height = value.get_height()
plt.text(value.get_x() + value.get_width()/2.,
1.002*height,'%d' % int(height), ha='center', va='bottom')
但是,条形图显示时条形图上没有值,如下所示。
IN: code(data['coast'])
OUT:
但是会出现以下错误消息
---------------------------------------------------------------------------
TypeError: 'AxesSubplot' object is not iterable
---------------------------------------------------------------------------
我如何解决上面的错误以获得下面的条形图。
发布于 2021-07-11 06:32:36
正如@Henry Ecker评论的那样,你应该在ax.patches上迭代。pandas plot函数返回轴,而不是补丁/矩形。
df = pd.DataFrame({
'coast': np.random.choice(['Cat1','Cat2'], size=20000, p=[0.9, 0.1])
})
def code(c):
plt.rc('figure', figsize=(10, 5))
ax = c.value_counts().plot(kind='bar')
for value in ax.patches:
height = value.get_height()
plt.text(value.get_x() + value.get_width()/2.,
1.002*height,'%d' % int(height), ha='center', va='bottom')
code(df.coast)
或者,只需绘制曲线图,并获得您自己的值。条形图的X轴只是一个从0到条数的数组(在本例中为2)。
df = pd.DataFrame({
'coast': np.random.choice(['Cat1','Cat2'], size=20000, p=[0.9, 0.1])
})
def code(c):
plt.rc('figure', figsize=(10, 5))
counts = c.value_counts()
ax = counts.plot(kind='bar')
for i in range(len(counts)):
ax.text(
x = i,
y = counts[i] + 600,
s = str(counts[i]),
ha = 'center', fontsize = 14
)
ax.set_ylim(0,25000)
code(df.coast)
https://stackoverflow.com/questions/68330318
复制相似问题