【问题标题】:Bar plot unique elements in a list条形图列表中的唯一元素
【发布时间】:2023-04-06 23:37:01
【问题描述】:

我正在尝试绘制列表中每个元素的数量:

x=[1,1,2]
list_pd = pd.DataFrame({'DrawnCards':x})
list_pd.head()
list_pd = list_pd.groupby('DrawnCards')['DrawnCards'].count() 

DrawnCards
1    2
2    1
Name: DrawnCards, dtype: int64

plt.bar(list_pd.DrawnCards)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-117-7f4d4efd9a31> in <module>()
----> 1 plt.bar(list_pd.DrawnCards)

C:\Users\mesme\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   2968             if name in self._info_axis:
   2969                 return self[name]
-> 2970             return object.__getattribute__(self, name)
   2971 
   2972     def __setattr__(self, name, value):

AttributeError: 'Series' object has no attribute 'DrawnCards'

那么我需要将系列类型更改为 dataframe 吗?我有点卡住了。

【问题讨论】:

    标签: python python-3.x pandas matplotlib dataframe


    【解决方案1】:

    尝试直接调用系列的plot方法。

    g = list_pd.groupby('DrawnCards')['DrawnCards'].count()
    g.plot(kind='bar')
    

    或者,plt.bar:

    plt.bar(g.index, g.values) 
    

    【讨论】:

    • 但限制是使用matplotlib来绘制图形。
    • @Krishnendu 对你有好处! plot 内部调用matplotlib.pyplot.bar。
    • 有什么方法可以显式调用 matplotlib 来做到这一点?
    猜你喜欢
    • 2017-04-12
    • 2011-05-23
    • 2023-03-31
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多