python 使用matplotlib画图

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengzheku/article/details/79104619
#!/usr/bin/python
# encoding=utf-8

import sys
import matplotlib.pyplot as plt

reload(sys)
sys.setdefaultencoding('utf-8')

x = [1, 2, 3]
y = [5, 7, 4]

x2 = [1, 2, 3]
y2 = [10, 14, 12]

x3 = [5, 6, 7]
y3 = [10, 14, 12]

# 散点和折线图
plt.figure('Line')  # 指定图表名称
plt.plot(x, y, '.', label='First')  # 散点图,以'.'作为形状, 名字为First
plt.plot(x2, y2, label='Second')  # 折线图, 名字为Second
plt.xlabel('Plot Number')  # 创建X轴的名称
plt.ylabel('Important var')  # 创建Y轴的名称
plt.xlim(-2.5, 2.5)  # 设置X轴坐标范围
plt.ylim(-1, 1)  # 设置Y轴坐标范围

plt.title('Scatter Diagram\nLine Chart')  # 创建图的标题
plt.legend()  # 生成默认图例

# 条形图
plt.figure('Bar')  # 指定图表名称
plt.bar(x, y, label='One')  # 创建条形图,命名为One
plt.bar(x3, y3, label='Two', color='g')  # 创建条形图, 颜色为g:绿色, r:红色, b:蓝色,也可以用十六进制颜色代码:#000011
plt.legend()  # 生成默认图例
plt.xlabel('Bar Number')  # 创建X轴的名称
plt.ylabel('Bar Height')  # 创建Y轴的名称
plt.title('Bar Chart')  # 创建图的标题

# 直方图: 直方图非常像条形图,倾向于通过将区段组合在一起来显示分布
plt.figure('Histogram')  # 指定图表名称
population_ages = [22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]
bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130]
plt.hist(population_ages, bins, histtype='bar', rwidth=0.8)
plt.xlabel('Histogram Number')  # 创建X轴的名称
plt.ylabel('Histogram Height')  # 创建Y轴的名称
plt.title('Histogram Chart')  # 创建图的标题
plt.legend()  # 生成默认图例

# 散点图
plt.figure('Scatter')  # 指定图表名称
x4 = [1, 2, 3, 4, 5, 6, 7, 8]
y4 = [5, 2, 4, 2, 1, 4, 5, 2]

plt.scatter(x4, y4, label='Scatter', color='k', s=25, marker="o")

plt.xlabel('x')
plt.ylabel('y')
plt.title('Scatter Chart')
plt.legend()

# 堆叠图
plt.figure('Stack')  # 指定图表名称
days = [1, 2, 3, 4, 5]
sleeping = [7, 8, 6, 11, 7]
eating = [2, 3, 4, 3, 2]
working = [7, 8, 7, 2, 2]
playing = [8, 5, 7, 8, 13]

plt.plot([], [], color='m', label='Sleeping', linewidth=5)
plt.plot([], [], color='c', label='Eating', linewidth=5)
plt.plot([], [], color='r', label='Working', linewidth=5)
plt.plot([], [], color='k', label='Playing', linewidth=5)

plt.stackplot(days, sleeping, eating, working, playing, colors=['m', 'c', 'r', 'k'])

plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Stack Chart')


# 饼图
plt.figure('Pie')  # 指定图表名称
slices = [7, 2, 2, 13]
activities = ['sleeping', 'eating', 'working', 'playing']
cols = ['c', 'm', 'r', 'b']

plt.pie(slices,
        labels=activities,
        colors=cols,
        startangle=90,
        shadow=True,
        explode=(0, 0.1, 0, 0),
        autopct='%1.1f%%')
plt.title('Pie Chart')

plt.show()  # 画图

猜你喜欢

转载自blog.csdn.net/fengzheku/article/details/79104619