pyplot 画图

参考 点击打开链接

1. 使用 plt.plot() 画 折线图

import matplotlib.pyplot as plt
import pandas as pd
x = [1, 3, 7, 8, 12, 14, 17, 25, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40] 
y = [3, 5, 6, 10, 13, 23, 24, 27, 30, 28, 22, 12, 15, 16, 11, 8, 7, 15, 25]
plt.plot(x, y, label='y=f(x)')
plt.xlabel('key')    # xlabel 方法指定 x 轴显示的名字
plt.ylabel('value')    # ylabel 方法指定 y 轴显示的名字
plt.title('k-v trend')
plt.legend()    # legend 是在图区显示label,即上面 .plot()方法中label参数的值
plt.show()

结果如下:


2. 使用 plt.bar() 画 条形图

import matplotlib.pyplot as plt

#在条形图的顶部添加y值的标注
def label_y_value(rects):
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width() / 2. - 0.2, 1.03 * height, '%s' % float(height))

rects1 = plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
rects2 = plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
label_y_value(rects1)
label_y_value(rects2)
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('show bar chart')
plt.show()

3. 使用 plt.hist() 画 直方图

# 条形图是给定 x 和对应的 y,根据 x 和 y 作图; 直方图是给定 x 和 bins,以 x 落入 bin 区间的数目为 y 作图
import matplotlib.pyplot as plt
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 = [i * 10 for i in range(0, 13)]
plt.hist(population_ages, bins, histtype='bar', rwidth=0.8)
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(bins)    # xticks(list) 使用list的值进行 x 轴刻度的标识
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

4. 使用 plt.scatter() 画 散点图

import numpy as np
import matplotlib.pyplot as plt

# plt.text(x, y, str) ---> 在点(x, y)处添加注释 str
# plt.annotate(str,xy=(x1, y1), xytext=(x2, y2), arrowprops=dict(arrowstyle="->",connectionstyle="arc3")) --->
# 在点 xytext 和 xy 之间添加注释 str,其中 xytext 是文本起点,点 xy 是箭头终点,arrowtypes指定箭头的样式

x = np.linspace(start=0, stop=100, num=11)
y = np.linspace(start=0, stop=100, num=11)
# plt.plot(x, y)
plt.scatter(x, y)
plt.text(x[1], y[1] - 5, ' plt.text') # 在 指定坐标(x[1], y[1] - 5)处添加文本 str(y[1])
# plt.fill_between(x, 0, y)
plt.annotate('plt.annotate', xy=(x[2], y[2]+2), xytext=(x[2] - 5, y[2] + 20), arrowprops=dict(arrowstyle="->",connectionstyle="arc3"))
plt.show()

5. 使用 plt.pie() 画 饼状图

#饼图
#饼图很像堆叠图,只是它们位于某个时间点。 通常,饼图用于显示部分对于整体的情况,通常以%为单位。

import matplotlib.pyplot as plt

slices = [7,2,2,13] # 即 activities 分别占比 7/24, 2/, 2/24, 13/24
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('Interesting Graph\nCheck it out')
plt.show()

6. 使用 plt.stackplot() 画 堆叠图

#堆叠图
#堆叠图用于表示部分对整体随时间变化的趋势,例如表示随着天数的变化,每天中 吃饭 睡觉 洗衣服分别占了多少时间
#区别于饼图的地方在于,饼图反映的是在某个时间点部分对整体的情况

import matplotlib.pyplot as plt

# 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.stackplot(days, sleeping,eating,working,playing, colors=['m','c','r','k'])
# plt.xlabel('x')
# plt.ylabel('y')
# plt.title('Interesting Graph\nCheck it out')
# plt.show()

#以上是普通的堆叠图,它的缺点是:
# 无法生产图例对线条进行说明,使用户在单纯看图的时候无法了解各线条分别代表什么情况

# 以下是改进版的堆叠图,区别于以上的地方在于:
# 它在画堆叠图之前先画了对应数据的普通线条图,然后legend方法根据线条图的label生成图例

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.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

7. 其它一些设置图表属性的方法

import matplotlib.pyplot as plt
import random
# ax = plt.subplot(a,b,c) 表示:
# 把整个图区划分为 a 行 b 列,返回第 c 个子图;当a,b,c都小于10的时候,可以写作 subplot(abc)

# ax.set_xticks(x)表示:设置x轴上的刻度
# ax.tick_params(axis='x', colors='#f06215') 表示:设置x轴刻度的颜色
# xticks_labels = ax.xaxis.get_ticklabels() 表示: 获取 ax 视图中 x 轴刻度 label 列表
# xticks_label.set_rotation(-45) 表示:对x轴刻度 label 进行旋转(旋转-45度)
# ax.axhline(5, color='k', linewidth=5) 表示:添加一条与x轴水平的线

# plt.xlabel('key', color='r') 表示:把 x 轴显示为 key,key的颜色为red;
# 以上写法等价于以下写法
# plt.xlabel('key') 并且 ax.xaxis.label.set_color('r'')

# ax.fill_between(x, 50, y, color = "g", alpha = 0.3) == ax.fill_between(x, y, 50, color = "g", alpha = 0.3)
# 以上两种写法都表示:使用green色,在x的取值范围内,填充函数 y=f(x) 与函数 y=50 之间的区域

# spine = ax.spines['left' / 'top' / 'right' / 'right'] 表示: 获取图区上下左右对应的边框
# spine.set_color('c') 表示:设置边框的颜色
# spine.set_linewidth(3) 表示:设置边框的线条宽度

# plt.grid() 表示:在图区显示方格线

x = [i + 1 for i in range(0, 20)]
y = [random.randint(0, 100) for i in range(0, 20)]
ax = plt.subplot(111)
plt.plot(x, y)
plt.grid()

ax.set_xticks(x)
ax.set_yticks([ydot * 10 for ydot in range(0, 10)])
plt.xlabel('key')
ax.xaxis.label.set_color('r')

# 对 y 值在 50 上下分别使用不同的颜色填充
ax.fill_between(x, 50, y, facecolors='g', alpha=0.5, where=([yg > 50 for yg in y]))
ax.fill_between(x, 50, y, facecolors='r', alpha=0.5, where=([yg < 50 for yg in y]))

#画边框,即整个函数图区的边缘
ax.spines['left'].set_color('c')
ax.spines['top'].set_color('g')
ax.spines['right'].set_color('b')
ax.spines['bottom'].set_color('r')
ax.spines['right'].set_linewidth(3)

ax.tick_params(axis='x', colors='#f06215')

ax.axhline(5, color='k', linewidth=5)#添加一条与x轴水平的线

for label in ax.xaxis.get_ticklabels():
    label.set_rotation(-45)#对x轴刻度进行旋转

plt.show()



  • 9
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值