【问题标题】:Plotting and labeling each bin in a histogram在直方图中绘制和标记每个 bin
【发布时间】:2020-01-08 17:25:20
【问题描述】:

我有一个包含不同情绪类别(标签)的数据集。您可以从下面代码中定义的“标签”变量中查看哪些类别。这些类别中的每一个在此数据集中都有不同数量的可用数据,我试图通过直方图箱来表示数据集的分布。

import matplotlib.pyplot as plt
import numpy as np
#labels inside emo variable, however they are labeled with numbers from 0 to 6 in sequence according to labels variable
labels = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise','neutral']
labels_np = np.array(labels)
#df_training is holding the train_set.csv, where I am selecting a single column which is 'emotion' 
emo = df_training["emotion"].hist()
plt.plot(labels_np,emo)

df_training['emotion']:

这是我得到的错误:

**ValueError:** x and y must have same first dimension, but have shapes (7,) and (1,)

这是所需的输出:

【问题讨论】:

  • 除非您向他们提供Minimal, Complete, and Verifiable example,否则人们很难帮助您
  • 至于代码部分,我已经给出了我所拥有的一切,我将尝试解释变量可能是什么,至于我想要实现的目标我想我已经描述了所有需要的东西,包括图片。
  • 你需要给df_training
  • 希望它现在更清楚,我已经在代码中评论了
  • 如您所见,通常如果我不在情节中包含 labels_np ,我会将这些垃圾箱标记为从 0 开始(生气)到 6 (中性),并且我正在尝试使用上面的方法将它们命名为图片!

标签: python pandas matplotlib histogram


【解决方案1】:

您似乎只想绘制直方图并设置正确的标签。 df_training.hist 已经绘制了一个直方图,但使用 0,1,2,... 作为 x-labels。 您可以通过调用 plt.xticks 来更改它。由于条形的中心位于 0.5,1.5,2.5,... 的位置,因此将刻度放在那里会使所有内容对齐。

由于您的数据仅包含从 0 到 6 的值,因此最好只有 7 个 bin,因此 8 个边界,hist 可以称为bins=range(8)。默认bins=10,绝对不是你想要的。

在下面的代码中,我删除了 x-grid 线,因为它们令人不安并且并不真正需要。 edgecolor 设置为ec='white' 以更好地区分条形。 df_training 的 'emotion' 列填充了一些随机数据。

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

labels = ['angry', 'disgust', 'fear', 'happy', 'sad', 'surprise','neutral']
df_training = pd.DataFrame( {'emotion': np.random.randint(0, 7, 100)})
emo = df_training.hist(column='emotion', ec='white', bins=range(8))
plt.grid(False, axis='x')
plt.xticks(ticks=np.arange(0.5,6.6,1), labels=labels)
plt.show()

【讨论】:

    猜你喜欢
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-04-03
    相关资源
    最近更新 更多