呆鸟的Python数据分析我爱编程数据分析技术帖

python利用pandas、matplotlib和wordcl

2017-08-29  本文已影响1214人  matianhe

开发环境还是和之前一样,需要安装pandas,numpy,matplotlib,scipy,jieba, wordcloud库,安装方法可以自行百度。

转载请注明地址:python利用pandas、matplotlib和wordcloud做数据分析
分析结果: 用python对鹿晗微博进行数据分析

首先介绍两个自己写的函数,下面会用到,一个是分词,另一个是返回一个dataframe的函数

def cut_zh(self, sql, cut=False):
    with connect() as cur:
        cur.execute(sql)
        result = cur.fetchall()
        words = map(lambda word: word[0], result)
        words = list(words)
    if cut:
        pattern = re.compile(r'[\u4e00-\u9fa5_a-zA-Z0-9]+')
        words = re.findall(pattern, str(result))
        words = ' '.join(words)
        jieba.load_userdict("source/dict.txt")
        words = jieba.cut(words)
        words = filter(lambda word: word != ' ', words)
        words = list(words)
    return words

def make_df(self, words, stopword=None):
    my_df = pd.DataFrame({'segment': words})
    if stopword:
        stopwords = pd.read_csv(stopword, names=['stopword'],
                                encoding='utf-8')
        my_df = my_df[~my_df.segment.isin(stopwords.stopword)]
        my_df = my_df.groupby(['segment'])['segment'].agg({'count': np.size})
        my_df = my_df.reset_index().sort_values(['count'], ascending=False)
    return my_df

1. 制作词云

def draw_wc(self, words, stopword=None, title=''):
    if stopword:
        data = self.make_df(words, stopword)
    else:
        data = self.make_df(words)
    bg_pic = imread('source/luhan.jpg')
    wordcloud = WordCloud(background_color='black', max_font_size=110,
                          mask=bg_pic, min_font_size=10, mode='RGBA',
                          font_path='source/simhei.ttf')
    word_frequence = {x[0]: x[1] for x in data.values}
    wordcloud = wordcloud.fit_words(word_frequence)
    plt.title(title, fontsize=16)
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.show()

先贴一下matplotlib官方文档,详细的参数在这里都有解释

2. 制作饼图

def draw_pie(self, words, stopword=None, title=''):
    if stopword:
        data = self.make_df(words, stopword)
    else:
        data = self.make_df(words)
    data = data[0:10].values
    x = [count[1] for count in data]
    y = [name[0] for name in data]
    expl = list(0 for i in range(len(x)))
    expl[0] = 0.1
    plt.title(title, fontsize=16)
    plt.pie(x, labels=y, autopct='%1.0f%%', pctdistance=0.8, shadow=True,
            startangle=60, explode=expl)
    plt.axis('equal')
    plt.legend()
    plt.show()

3. 制作柱状图

def draw_bar(self, words, stopword=None, title=''):
    if stopword:
        data = self.make_df(words, stopword)
    else:
        data = self.make_df(words)
    data = data[0:30].values
    x = range(len(data))
    y = [count[1] for count in data]
    label = [name[0] for name in data]
    plt.bar(x, y, tick_label=label, color='rgbycmk', alpha=0.3)
    plt.xticks(rotation=30)
    plt.title(title, fontsize=16)
    for a, b in zip(x, y):
        plt.text(a, b+0.05, '%.0f' % b, ha='center', fontsize=10)
    plt.show()
def draw_barh(self, words, stopword=None, title=''):
    if stopword:
        data = self.make_df(words, stopword)
    else:
        data = self.make_df(words)
    data = data[0:30].values
    x = range(len(data))
    y = [count[1] for count in data]
    label = [name[0] for name in data]
    plt.barh(x, y, tick_label=label, color='rgbycmk', alpha=0.2)
    plt.title(title, fontsize=16)
    plt.xlabel('人数', fontsize=12)
    for a, b in zip(x, y):
        plt.text(b, a, '%.0f' % b, ha='left', va='center', fontsize=10)
    plt.show()

折线图

def draw_plot_birth(self, words, stopword=None, title=''):
    if stopword:
        data = self.make_df(words, stopword)
    else:
        data = self.make_df(words)
    x_sort = data.sort_values('segment').values[42:110]
    x = range(len(x_sort))
    y = [name[1] for name in x_sort]
    plt.plot(x, y, 'b--')
    plt.title(title)
    plt.xlabel('年份', fontsize=14)
    plt.ylabel('数量', fontsize=14)
    plt.xticks(x, [i[0] for i in x_sort], rotation=90)
    plt.show()
上一篇 下一篇

猜你喜欢

热点阅读