Darui Shi
2016-11-14 12:59
采纳率: 100%
浏览 5.3k

Python中matplotlib.pyplot.hist显示x must be 1D or 2D

求问大神:
用来做社会网络分析中的直方图的,代码如下:

 import networkx as net
import matplotlib.pyplot as plot

def sorted_map(map):
    ms=sorted(map.items(),key=lambda k:(-k[1],k[0]))
    return ms

g=net.read_pajek('russians.net')
deg=net.degree(g)

ds=sorted_map(deg)
print(ds[0:9])

h=plot.hist(deg.values(),100)
plot.loglog(h[1][1:],h[0])

结果运行之后显示的是:

 Traceback (most recent call last):
  File "degreeCentrality.py", line 14, in <module>
    h=plot.hist(deg.values())
  File "C:\Users\19665\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\pyplot.py", line 2965, in his
t
    stacked=stacked, data=data, **kwargs)
  File "C:\Users\19665\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\__init__.py", line 1819, in i
nner
    return func(ax, *args, **kwargs)
  File "C:\Users\19665\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\axes\_axes.py", line 5935, in
 hist
    x = _normalize_input(x, 'x')
  File "C:\Users\19665\AppData\Local\Programs\Python\Python35\lib\site-packages\matplotlib\axes\_axes.py", line 5877, in
 _normalize_input
    "{ename} must be 1D or 2D".format(ename=ename))
ValueError: x must be 1D or 2D

找了一下午了,都没找到相关的解决方法,跪求指点!

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • Darui Shi 2016-11-14 13:19
    已采纳

    只需要将倒数第二行的h=plot.hist(deg.values(),100)改为h=plot.hist(list(deg.values()),100)就可以了,python 3.x

    打赏 评论
  • 喜欢吃绝味鸭脖 2021-03-09 02:34

    求解答:

    #RFM分析(假设现在是2017/11/25)
    from datetime import datetime 
    
    #最近一次购买距离现在的天数
    data['date']=pd.to_datetime(data['date'])
    recent_buy=data[data.behavior=='购买'].groupby('user_id')['date'].apply(lambda x: datetime(2017,12,25)-x.sort_values().iloc[-1]).reset_index().rename(columns={'date':'recent'})
    recent_buy.recent=recent_buy.recent.map(lambda x: x.days)
    
    #购买频率(购买次数)
    fred_buy=data[data.behavior=='购买'].groupby('user_id').date.count().reset_index().rename(columns={'date':'fred'})
    #rfm
    
    recent_fred=pd.merge(recent_buy,fred_buy,on='user_id')
    #为实现自动细分,将使用R和F变量的80%分位数
    quantiles=recent_fred.quantile(q=[0.8])
    
    recent_fred['R']=np.where(recent_fred['recent']<=int(quantiles.recent.values),2,1)
    recent_fred['F']=np.where(recent_fred['fred']<=int(quantiles.fred.values),1,2)
    recent_fred['rfm']=recent_fred.R.map(str)+recent_fred.F.map(str)
    
    #打标签,时间越近次数越多越重要
    labels = {'12':'流失客户','22': '明星客户','11':'次要客户','21':'新客户'}
    recent_fred['labels']= recent_fred['rfm'].apply(lambda x: labels[x])
    rfm=pd.DataFrame(recent_fred['labels'].value_counts())
    
    plt.figure(figsize=(10,7))
    plt.pie(rfm.values,labels=rfm.index,explode=(0.05,0,0,0),colors=['red','yellowgreen','gold','orange'],autopct='%1.1f%%',textprops={'fontsize':15})
    plt.legend()
    plt.axis('equal')
    plt.title('客户类群占比',fontsize=18)
    
    
    打赏 评论

相关推荐 更多相似问题