matplotlib绘图

函数subplot表示在一个图片中绘制一个或多个图表
fig表示整张图片
ax表示整张图片的各个图表

import matplotlib.pyplot as plt
squares = [1,4,9,16,25]
fig,ax = plt.subplots()
ax.plot(squares)
plt.show()

在这里插入图片描述

  1. linewidth决定绘制线条的粗细
  2. tick_params设置刻度
  3. labelsize设置字号
import matplotlib.pyplot as plt
plt.rcParams['font.sas-serig']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
fig,ax = plt.subplots()
ax.plot(input_values,squares,linewidth=3)

# 设置图表标题,并给坐标轴加上标签
ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)

ax.tick_params(axis='both',labelsize=10)

plt.show()

在这里插入图片描述

15.2.3 Matplotlib内置样式
import matplotlib.pyplot as plt
plt.style.available
['Solarize_Light2',
 '_classic_test',
 '_classic_test_patch',
 '_mpl-gallery',
 '_mpl-gallery-nogrid',
 'bmh',
 'classic',
 'dark_background',
 'fast',
 'fivethirtyeight',
 'ggplot',
 'grayscale',
 'seaborn',
 'seaborn-bright',
 'seaborn-colorblind',
 'seaborn-dark',
 'seaborn-dark-palette',
 'seaborn-darkgrid',
 'seaborn-deep',
 'seaborn-muted',
 'seaborn-notebook',
 'seaborn-paper',
 'seaborn-pastel',
 'seaborn-poster',
 'seaborn-talk',
 'seaborn-ticks',
 'seaborn-white',
 'seaborn-whitegrid',
 'tableau-colorblind10']
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5]
squares = [1,4,9,16,25]
plt.style.use('seaborn')
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
fig,ax = plt.subplots()

ax.plot(input_values,squares,linewidth=3)

# 设置图表标题,并给坐标轴加上标签
ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)

ax.tick_params(axis='both',labelsize=10)

plt.show()

在这里插入图片描述

15.2.4 使用scatter()绘制散点图

import matplotlib.pyplot as plt
x_values = [1,2,3,4,5]
y_values = [1,4,9,16,25]
plt.style.use('seaborn')
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
fig,ax = plt.subplots()
ax.scatter(x_values,y_values,s=200)

ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)

ax.tick_params(axis='both',which='major',labelsize=10)

plt.show()

在这里插入图片描述

0~1的小数值分别为红绿蓝的分量

import matplotlib.pyplot as plt
x_values = range(1,1001)
y_values = [x**2 for x in x_values]
plt.style.use('seaborn')
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
fig,ax = plt.subplots()
ax.scatter(x_values,y_values,color=(0,0.8,0),s=10)

ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)

ax.tick_params(axis='both',which='major',labelsize=10)

# 设置每个坐标轴的取值范围  x轴位0~1000 y轴为0~1100000
ax.axis([0,1100,0,1100000])
plt.show()

在这里插入图片描述

15.2.8 使用颜色映射

pyplot中所有的颜色映射在matplotlib–>Examples—>Coloe—>Colormaps reference中

import matplotlib.pyplot as plt
x_values = range(1,1001)
y_values = [x**2 for x in x_values]
plt.style.use('seaborn')
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
fig,ax = plt.subplots()
ax.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,s=10)

ax.set_title("平方数",fontsize=24)
ax.set_xlabel("值",fontsize=14)
ax.set_ylabel("值的平方",fontsize=14)

ax.tick_params(axis='both',which='major',labelsize=10)

# 设置每个坐标轴的取值范围  x轴位0~1000 y轴为0~1100000
ax.axis([0,1100,0,1100000])
plt.savefig('squares_plot.png',bbox_inches='tight')
plt.show()

在这里插入图片描述

自动保存图表,**bbox_inches=‘tight’**表示将图表多余的空白区域裁剪掉

15.3.3绘制随机漫步图

from random import choice
class RandomWalk:
    def __init__(self,num_points=50000):
        self.num_points = num_points
        self.x_values=[0]
        self.y_values=[0]
    def fill_walk(self):
        while len(self.x_values) < self.num_points:
            x_direction = choice([1,-1])
            x_distance = choice([0,1,2,3,4])
            x_step = x_direction * x_distance
            
            y_direction = choice([1,-1])
            y_distance = choice([0,1,2,3,4])
            y_step = y_direction * y_distance
            
            if x_step==0 and y_step==0:
                continue
            x = self.x_values[-1]+x_step
            y = self.y_values[-1]+y_step
            
            self.x_values.append(x)
            self.y_values.append(y)
        print(len(self.x_values))
import matplotlib.pyplot as plt
rw = RandomWalk()
rw.fill_walk()
plt.style.use('classic')
fig,ax=plt.subplots()
ax.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
50000

在这里插入图片描述

import matplotlib.pyplot as plt
while True:
    rw = RandomWalk()
    rw.fill_walk()
    plt.style.use('classic')
    fig,ax=plt.subplots()
    ax.scatter(rw.x_values,rw.y_values,s=15)
    plt.show()
    keep_running = input("Make another walk?(y/n):")
    if keep_running == 'n':
        break
50000

在这里插入图片描述

Make another walk?(y/n):
50000

在这里插入图片描述

Make another walk?(y/n):
50000

在这里插入图片描述

Make another walk?(y/n):
50000

在这里插入图片描述

Make another walk?(y/n):
50000

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-t0GVv6nU-1645690802713)(output_18_9.png)]

Make another walk?(y/n):n

**ax.get_xaxis().set_visible(False)**隐藏坐标轴 figsize指生成图形的尺寸 dpi图形的分辨率

while True:
    rw = RandomWalk()
    rw.fill_walk()
    plt.style.use('classic')
    fig,ax=plt.subplots(figsize=(10,6),dpi=128)
    point_numbers = range(rw.num_points)
    ax.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors="none",s=15)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    plt.show()
    keep_running = input("Make another walk?(y/n):")
    if keep_running == 'n':
        break
50000

在这里插入图片描述

Make another walk?(y/n):n

15.4.3 掷骰子

from random import randint
class Die:
    def __init__(self,num_sides=6):
        self.num_sides = num_sides
    def roll(self):
        return randint(1,self.num_sides)
die = Die()
results=[]
for roll_num in range(100):
    result = die.roll()
    results.append(result)
print(results)
[6, 5, 6, 2, 4, 4, 6, 1, 4, 4, 4, 2, 3, 6, 3, 5, 3, 5, 2, 4, 6, 4, 4, 3, 4, 3, 1, 3, 4, 2, 5, 3, 1, 4, 2, 4, 3, 5, 2, 1, 1, 2, 6, 2, 1, 2, 4, 6, 3, 3, 4, 6, 3, 2, 1, 6, 1, 4, 1, 2, 6, 4, 3, 3, 1, 5, 6, 5, 4, 6, 3, 5, 4, 6, 3, 2, 2, 3, 2, 4, 2, 2, 2, 3, 4, 5, 1, 1, 1, 5, 5, 4, 6, 1, 2, 2, 6, 2, 6, 6]
import csv
filename= "sitka_weather_07-2018_simple.csv"
with open(filename) as f:
    reader = csv.reader(f)
    header_row=next(reader)
    for index,colum_header in enumerate(header_row):
        print(index,colum_header)
0 STATION
1 NAME
2 DATE
3 PRCP
4 TAVG
5 TMAX
6 TMIN
import csv
filename= "sitka_weather_07-2018_simple.csv"
with open(filename) as f:
    reader = csv.reader(f)
    header_row=next(reader)
    highs = []
    for row in reader:
        high = int(row[5])
        highs.append(high)

print(highs)
[62, 58, 70, 70, 67, 59, 58, 62, 66, 59, 56, 63, 65, 58, 56, 59, 64, 60, 60, 61, 65, 65, 63, 59, 64, 65, 68, 66, 64, 67, 65]
绘制温度图表
import csv
import matplotlib.pyplot as plt
filename= "sitka_weather_07-2018_simple.csv"
with open(filename) as f:
    reader = csv.reader(f)
    header_row=next(reader)
    highs = []
    for row in reader:
        high = int(row[5])
        highs.append(high)

plt.style.use('seaborn')
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
fig,ax = plt.subplots()
ax.plot(highs,c='red')

ax.set_title("2018年7月每日最高温度",fontsize=24)
ax.set_xlabel('',fontsize=16)
ax.set_ylabel("温度(F)",fontsize=16)
ax.tick_params(axis='both',which='major',labelsize=16)
plt.show()

在这里插入图片描述

from datetime import datetime
first_date = datetime.strptime('2018-07-01','%Y-%m-%d')
print(first_date)
2018-07-01 00:00:00
  1. **fig.autofmt_xdate()**表示绘制倾斜的日期标签
  2. ax.fill_between表示给两个区域着色
import csv
from datetime import datetime
import matplotlib.pyplot as plt
filename= "sitka_weather_07-2018_simple.csv"
with open(filename) as f:
    reader = csv.reader(f)
    header_row=next(reader)
    dates,highs,lows = [],[],[]
    for row in reader:
        current_data = datetime.strptime(row[2],'%Y-%m-%d')
        high = int(row[5])
        low = int(row[6])
        dates.append(current_data)
        highs.append(high)
        lows.append(low)
plt.style.use('seaborn')
plt.rcParams['font.sans-serif']=['Microsoft YaHei']
fig,ax = plt.subplots()
ax.plot(dates,highs,c='red')
ax.plot(dates,lows,c='blue')
# 给两个区域着色
ax.fill_between(dates,highs,lows,facecolor='blue',alpha=0.1)

ax.set_title("2018年7月每日最高温度",fontsize=24)
ax.set_xlabel('',fontsize=16)
ax.set_ylabel("温度(F)",fontsize=16)
fig.autofmt_xdate()
ax.tick_params(axis='both',which='major',labelsize=16)
plt.show()

在这里插入图片描述


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值