【问题标题】:How to plot bar chart in Python using matplotlib.pyplot ? Argument height must be 'xxxx' or scalar如何使用 matplotlib.pyplot 在 Python 中绘制条形图?参数高度必须是 'xxxx' 或标量
【发布时间】:2018-01-28 20:02:24
【问题描述】:

我有一个名为“train”的数据框,其中包含多个变量。一个这样的变量是“行业”。 “行业”列的前 10 个元素如下:

train['industry'][:10]
0    Office supplies    
1    Unknown            
2    Misc services      
3    Social services    
4    Unknown            
5    Manufacturing      
6    Social services    
7    Office supplies    
8    Entertainment      
9    Construction       
Name: industry, dtype: object

我正在尝试使用 matplotlib.pyplot 作为 plt 库绘制条形图,x 轴为行业类型,y 轴为频率。我不太确定“高度”参数的值应该是什么?

plt.bar(train['industry'], height = )

【问题讨论】:

  • height 参数是您希望条形的高度。这意味着x 是数据框中独特行业的序列,height 是它们出现的次数。 pyplot.bar 不会为你计算。
  • @PaulH 那么我是否必须分别计算它们的频率才能绘图?在 R 中,使用 ggplot2 非常简单 -_-
  • pyplot.bar,是的。使用其他高级库,您可以一步完成。不过,matplotlib 故意是一个低级库。
  • seaborn.factorplot 可以一步完成:seaborn.pydata.org/generated/seaborn.factorplot.html

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


【解决方案1】:

身高是你的频率。这是example

  1. 制作长度为len(train.index)的数组

  2. 制作没有行业名称的条形图 - plt.bar(array, frequency)。频率/高度不能是字符串。它必须是数字的。如果不是,请使用pd.to_numeric

  3. 进行转换
  4. 将行业名称放入数组中

  5. 使用set_xticklabels(industries)更改标签

【讨论】:

  • plt.bar(array, frequency) 究竟是什么意思?它究竟是如何使用的?
猜你喜欢
  • 2017-03-12
  • 1970-01-01
  • 2014-06-15
  • 2018-05-15
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
  • 2018-04-23
相关资源
最近更新 更多