Matplotlib

作者: 青椒rose炒饭 | 来源:发表于2019-07-01 12:46 被阅读0次

学习源
Matplotlib需要和NumPy一起使用也可以和图形工具包PyQt,wxPython一起使用。

import  numpy as np
import matplotlib.pyplot as plt
#设置x的范围,0 - 4π,每次取值点增加0.01,让曲线圆滑
x = np.arange(0,4 * np.pi,0.01)
#直接写为函数
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.arctan(x)

#在高为2,宽2的面板第一个位置画sin,布局如下
#     1     2
#     3     4
#指定位置
plt.subplot(2,2,1)
#设置标题
plt.title('sin')
#画图,h 表示样本点显示为六边形标记1 ,一旦设置了样本点显示就默认为离散图
#  r表示为红色
plt.plot(x,y1,'hr')

plt.subplot(2,2,2)
plt.title('cos')
#g 绿色
plt.plot(x,y2,'g')

plt.subplot(2,2,4)
plt.title('cos')
#b蓝色
plt.plot(x,y3,'b')
#显示画图面板
plt.show()
运行结果

关于设置标记点样式和线条颜色:
设置样式:

标记 属性 标记 属性
'-' 实线样式 '--' 短横线样式
'-.' 点划线样式 ':' 虚线样式
'.' 点标记 ',' 像素标记
'o' 圆标记 'v' 倒三角标记
'^' 正三角标记 '<' 左三角标记
'>' 右三角标记 '1' 下箭头标记
'2' 上箭头标记 '3' 左箭头标记
'4' 右箭头标记 's' 正方形标记
'p' 五边形标记 '*' 星形标记
'h' 六边形标记 1 'H' 六边形标记 2
'+' 加号标记 'x' X 标记
'D' 菱形标记 'd' 窄菱形标记
'|' 竖直线标记 '_' 水平线标记

设置线条颜色:

字符 颜色
'b' 蓝色
'g' 绿色
'r' 红色
'c' 青色
'm' 品红色
'y' 黄色
'k' 黑色
'w' 白色

绘制其他图

下面使用state_union 语料库阅读器,访问《国情咨文报告》的文本。计数每个文档中出现的men、women 和people。随时间的推移这些词的用法有什么变化?

from nltk.corpus import state_union
from matplotlib import pyplot as plt

result = {}#结果存储为字典类型,键是年,值是men,women,people的频率
#文件id为  1953-Eisenhower.txt  这样子的
result = {fileid[:4]:
              [
                  len([word for word in state_union.words(fileid) if word.lower() == 'men']),
                  len([word for word in state_union.words(fileid) if word.lower() == 'women']),
                  len([word for word in state_union.words(fileid) if word.lower() == 'people'])
              ]
              for fileid in state_union.fileids()
          }
print(result)
#x 轴为年
x = [int(year) for year in result.keys()]
men = [result[year][0] for year in result.keys()]
women = [result[year][1] for year in result.keys()]
people = [result[year][2] for year in result.keys()]

#绘制柱状图
plt.plot(x,men,'r')
plt.plot(x,women,'g')
plt.plot(x,people,'b')
plt.show()
运行结果

绘制柱状图

这个柱状图就画的很难受,会相互覆盖,我的是在代码中为x加0.1错开位置才没有被覆盖的。

import matplotlib.pyplot as plt
x1 = [1,3,5]
y1 = [1,3,5]

x2 = [1.1,3.1,5.1]
y2 = [2,4,6]

#画图,先画第一个,再画第二个
plt.bar(x1,y1,0.1,label="classA")
plt.bar(x2,y2,0.1,label="classB")
#显示标签
plt.legend()
plt.show()
运行结果

相关文章

网友评论

    本文标题:Matplotlib

    本文链接:https://www.haomeiwen.com/subject/yfpwcctx.html