Python matplotlib库的使用

来自CloudWiki
跳转至: 导航搜索

matplotlib的安装

python -m pip install -U pip setuptools
python -m pip install matplotlib
python -m pip list

matplotlib的使用

绘制散点图

>>> a = np.arange(0, 2.0*np.pi, 0.1)
>>> b = np.cos(a)
>>> pl.scatter(a,b)
>>> pl.show()

绘制饼图

import numpy as np
import matplotlib.pyplot as plt

#The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
colors = ['yellowgreen', 'gold', '#FF0000', 'lightcoral']
explode = (0, 0.1, 0, 0.1)              # 使饼状图中第2片和第4片裂开

fig = plt.figure()
ax = fig.gca()

ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
       autopct='%1.1f%%', shadow=True, startangle=90,
       radius=0.25, center=(0, 0), frame=True)   # autopct设置饼内百分比的格式
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
       autopct='%1.1f%%', shadow=True, startangle=45,
       radius=0.25, center=(1, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
       autopct='%1.1f%%', shadow=True, startangle=90,
       radius=0.25, center=(0, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
       autopct='%1.2f%%', shadow=False, startangle=135,
       radius=0.35, center=(1, 0), frame=True)


ax.set_xticks([0, 1])                    # 设置坐标轴刻度
ax.set_yticks([0, 1])

ax.set_xticklabels(["Sunny", "Cloudy"])  # 设置坐标轴刻度上的标签
ax.set_yticklabels(["Dry", "Rainy"])

ax.set_xlim((-0.5, 1.5))                 # 设置坐标轴跨度
ax.set_ylim((-0.5, 1.5))

ax.set_aspect('equal')                   # 设置纵横比相等

plt.show()

绘制词云

import random
import string
import wordcloud

def show(s):
    # 创建wordcloud对象
    wc = wordcloud.WordCloud(
        r'C:\windows\fonts\simfang.ttf', width=500, height=400,
        background_color='white', font_step=3,
        random_state=False, prefer_horizontal=0.9)
    # 创建并显示词云
    t = wc.generate(s)
    t.to_image().save('t.png')
    
# 如果空间足够,就全部显示
# 如果词太多,就按频率显示,频率越高的词越大
show('''hello world 董付国 董付国 董付国 董付国
 abc fgh yhnbgfd 董付国 董付国 董付国 董付国 Python great Python Python''')


返回 Python程序设计艺术