【问题标题】:matplotlib a histogram with strings on x-axismatplotlib x 轴上带有字符串的直方图
【发布时间】:2017-06-21 03:24:47
【问题描述】:

我想在一个非常基本的熊猫系列上做一个直方图。例如下面,我只是想让 x 轴显示“冰淇淋”、“巧克力”和“咖啡”,而 y 轴显示 2、3、1(计数)。这可能吗?请注意,第一列不是按顺序排列的,因为我已经过滤掉了 NaN 值。

print(data_null_false)
45    ice-cream
101   chocolate
102   ice-cream
103   coffee
112   chocolate
120   chocolate

fig, ax = plt.subplots()
ax.hist(rbr_null_false)
plt.show()

导致以下错误:

    ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-7d1a5e1bb62b> in <module>()
     28 
     29 fig, ax = plt.subplots()
---> 30 ax.hist(rbr_null_false)
     31 #plt.xlabel('index', fontsize=12);
     32 #plt.ylabel('prod_rollback_date', fontsize=12);

~/anaconda3/lib/python3.5/site-packages/matplotlib/__init__.py in inner(ax, *args, **kwargs)
   1810                     warnings.warn(msg % (label_namer, func.__name__),
   1811                                   RuntimeWarning, stacklevel=2)
-> 1812             return func(ax, *args, **kwargs)
   1813         pre_doc = inner.__doc__
   1814         if pre_doc is None:

~/anaconda3/lib/python3.5/site-packages/matplotlib/axes/_axes.py in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
   5993             xmax = -np.inf
   5994             for xi in x:
-> 5995                 if len(xi) > 0:
   5996                     xmin = min(xmin, xi.min())
   5997                     xmax = max(xmax, xi.max())

TypeError: len() of unsized object

【问题讨论】:

    标签: pandas numpy matplotlib histogram


    【解决方案1】:

    虽然你说你想要一个直方图,但它实际上是一个条形图。 “histogram 是数字数据分布的准确图形表示。”您的示例是分类数据。所以:

    import io
    
    import matplotlib.pyplot as plt
    import pandas as pd
    
    data = """45    ice-cream
    101 chocolate
    102 ice-cream
    103 coffee
    112 chocolate
    120 chocolate"""
    df = pd.read_table(io.StringIO(data), header=None)
    s = df[1]
    
    s.value_counts().plot(kind='bar')
    plt.show()
    

    【讨论】:

    • 有没有办法避免裁剪/剪裁问题?在随附的示例中,巧克力和奶油都被部分截断,对于稍长的字符串(10-15 个字符),可能很难理解它实际上应该是什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 2015-06-22
    • 2017-07-01
    • 2012-05-16
    • 2011-03-26
    • 1970-01-01
    相关资源
    最近更新 更多