python爬虫

matplotlib学习笔记

2020-07-02  本文已影响0人  苦海飘摇

matplotlib笔记

前言:最近学习了matplotlib,以下是我自己记得笔记,方便自己回顾。如果读者自己遇到了问题可以找找我的注释,或者直接给我留言。如果读者想学习matplotlib,请移步。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import font_manager
# 设置matplotlib支持中文
my_font = font_manager.FontProperties(fname='/System/Library/Fonts/PingFang.ttc')

my_font = font_manager.FontProperties(fname='/System/Library/Fonts/PingFang.ttc'),这里font_manager支持windos、macOS、linux三系统,fname为自己系统里的字体路径。如何是图例有中文plt.legend(prop=my_font),如果是其他地方直接fontproperties=my_font比如plt.xlabel('时间', fontproperties=my_font)

散点图

height = [161, 173, 182, 174, 170, 164]
weight = [50, 68, 80, 70, 69, 55]
plt.scatter(height, weight, s=100, c='r', marker="<", alpha=0.3)
plt.xlabel('height')
plt.ylabel('weight')
plt.xlim(160, 190)
plt.ylim(50, 85)
散点图

折线图

折线图1

x = np.linspace(-10, 10, 50)
y = x ** 2
plt.plot(x, y, c='r')
plt.xlabel('x')
plt.ylabel('y')
折线图1

折线图2

# delimiter代表以逗号分隔,skiprows代表跳过第一行标题行,usecols代表取那几行,converters将日期转化
date, shang, shen = np.loadtxt('1.csv', delimiter=',', converters={0: mdates.bytespdate2num('%Y/%m/%d')},
                               skiprows=1, usecols=(0, 1, 3), unpack=True)
print('data=', date)  # [735141. 735110. 735080..........
print('shang=', shang)
print('shen=', shen)

# plt.plot(date, shang)  # 默认为折线图
# 自动识别date并转换成时间, 默认为点图,-为折线,--为虚线
l1, = plt.plot_date(date, shang, linewidth=3.0, linestyle='--', c='blue', marker='o', label='shang')
l2, = plt.plot_date(date, shen, linewidth=1, linestyle='-', c='r', marker='<', label='shen')  # 如果希望在legend中给labels赋值后面必须有逗号
plt.legend(handles=[l1, l2], labels=['aaa', 'bbb'], loc='best')  # 这里的labels和上面的label有一个就可

# 边框设置,必须在x/yticks前面定义,不然x/yticks定义的旋转与中文支持将不起作用
ax = plt.gca()  # gca = 'get current axis'
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')  # 去掉顶部轴
ax.spines['bottom'].set_position(('data', 30))  # x轴和y轴的30对齐

# 更改横纵坐标值,横坐标为xticks,可设置旋转角度 rotation
# plt.yticks([10, 20, 30, 40, 50])
plt.yticks([10, 20, 30, 40, 50],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

# 横纵坐标加标签,fontproperties设置支持中文
plt.xlabel('时间', fontproperties=my_font)
plt.ylabel('盈利', fontproperties=my_font)
折线图2
  • linestylecolor可以写在一起比如l2, = plt.plot_date(date, shen, linewidth=1, linestyle='-', c='r', marker='<', label='shen')可以写成l2, = plt.plot_date(date, shen, 'r-', linewidth=1, marker='<', label='shen')
  • 边框设置,必须在x/yticks前面定义,不然x/yticks定义的旋转与中文支持将不起作用

条形图

竖排条形图

n = 12
X = np.arange(n)
y1 = (1 - X / n) * np.random.uniform(0.5, 1, n)
y2 = (1 - X / n) * np.random.uniform(0.5, 1, n)
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')

plt.bar(X, +y1, color='#9999ff', edgecolor='red')
plt.bar(X, -y2, width=1, color='#ff9999')
for x, y in zip(X, y1):
    # ha: horizontal alignment
    plt.text(x + 0.04, y + 0.05, '%.2f' % y, c='#9999ff', ha='center', va='bottom')
for x, y in zip(X, y2):
    # ha: horizontal alignment
    plt.text(x + 0.04, -y - 0.05, '%.2f' % -y, c='#ff9999', ha='center', va='top')
plt.xlim(-.5, n)
plt.ylim(-1.25, 1.25)
ax.spines['left'].set_color('none')
ax.spines['bottom'].set_position(('data', 0))
plt.yticks(())
竖排条形图

横排条形图

n = 12
X = np.arange(n)
y1 = (1 - X / n) * np.random.uniform(0.5, 1, n)
y2 = (1 - X / n) * np.random.uniform(0.5, 1, n)
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
plt.barh(X, y1, color='#9999ff')
plt.barh(X, -y2, color='#ff9999', edgecolor='red')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_position(('data', 0))
for x, y in zip(X, y1):
    # 虽然x,y轴颠倒了,但是在plt.text中依然是先定义横向坐标再定义纵向坐标
    # 因此这里应该是plt.text(y, x)
    plt.text(y + 0.06, x - 0.1, '%.2f' % y, c='#9999ff', ha='center')
for x, y in zip(X, y2):
    plt.text(-y - 0.07, x - 0.1, '%.2f' % -y, c='#ff9999', ha='center')
plt.xticks(())
横排条形图

分组

n = 12
X = np.arange(n)
y1 = (1 - X / n) * np.random.uniform(0.5, 1, n)
y2 = (1 - X / n) * np.random.uniform(0.5, 1, n)
ax = plt.gca()
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
shang, shen = np.loadtxt('1.csv', delimiter=',', skiprows=1, usecols=(1, 3), unpack=True)
nums = np.hstack((shang, shen))
x = np.arange(nums.shape[0])
bin_nums = (nums.max() - nums.min()) // 4
plt.hist(nums, int(bin_nums))
分组

等高线

def f(x, y):
    # the height function
    return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 - y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
# use plt.contourf to filling contours
# X, Y and value for (X, Y) point
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)
# use plt.contour to add contour lines
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
# adding label
plt.clabel(C, inline=True, fontsize=10)

plt.xticks(())
plt.yticks(())
等高线

饼状图

x = np.random.randint(1, 10, 4)
plt.figure(figsize=(5, 5), dpi=80)  # 图片大小和分辨率,需要定义在前面
plt.title('随机饼图', fontproperties=my_font)
plt.pie(x, explode=[0, 0, 0.1, 0], labels=['1', '2', '3', '4'],
        colors=['red', 'yellow', 'blue', 'green'])
plt.legend(loc='upper right', prop=my_font)  # prop为设置支持中文
饼状图

练习:请绘出以下图形:

上一篇 下一篇

猜你喜欢

热点阅读