matplotlib绘图

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

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

matplotlib绘图
  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()

matplotlib绘图

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()

matplotlib绘图

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()

matplotlib绘图

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)

ax.axis([0,1100,0,1100000])
plt.show()

matplotlib绘图

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)

ax.axis([0,1100,0,1100000])
plt.savefig('squares_plot.png',bbox_inches='tight')
plt.show()

matplotlib绘图

自动保存图表,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

matplotlib绘图
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

matplotlib绘图
Make another walk?(y/n):
50000

matplotlib绘图
Make another walk?(y/n):
50000

matplotlib绘图
Make another walk?(y/n):
50000

matplotlib绘图
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

matplotlib绘图
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()

matplotlib绘图
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()

matplotlib绘图

Original: https://blog.csdn.net/CheatMyself/article/details/123114654
Author: 小人物CM
Title: matplotlib绘图



相关阅读

Title: 如何从零开始搭建基于Django的后端项目

web项目开发之开发环境的搭建

开始开发一个Django项目前,如何搭建虚拟环境呢?
假设初始配置为:linux ubuntu20.04 pycharm专业版
假设项目名称为: Pcone

1. 创建虚拟环境

打开终端,利用anaconda创建虚拟环境

cd ~/Desktop
conda create -n pcone python=3.8

2. 准备好外部依赖

注册云服务器、云存储服务、防水墙、短信验证、视频服务等第三方工具。

[En]

Register the registered third-party tools such as cloud servers, cloud storage services, waterproof walls, SMS verification, video services, etc.

3. 安装项目会用到的相关依赖包

依赖包:django、djangorestframework、pillow、PymySQL
此处使用douban源,以便加快安装速度

pip install django==3.2.5  -i https://pypi.douban.com/simple
pip install djangorestframework  -i https://pypi.douban.com/simple
pip install Pillow  -i https://pypi.douban.com/simple
conda install  -c conda-forge PymySQL

4. 搭建服务端

创建项目目录:

cd ~/Desktop

mkdir pcone
cd pcone

django-admin startproject pconeapi

此时桌面会出现 /pcone/pconeapi这个文件夹,打开pycharm,把pconeapi拖拽进去即可

5. 在pycharm中设置虚拟环境

File-Settings-Project:pcone-Python Interpreter
选择步骤1中创建的虚拟环境作为Python Interpreter

6. 启动django项目

pconapi打开后,自带一个manage.py文件,是项目的启动文件
按照下图进行配置后,就可以通过本地IP的8000端口(http://127.0.0.1:8000)访问项目了。

matplotlib绘图
matplotlib绘图

; 7. 调整目录结构

pcone/
  ├── docs/
  ├── pconeweb/
  ├── pconeapi/
       ├── manage.py
       ├── logs/
       ├── pconeapi/
       │    ├── apps/
       │    ├── libs/
       │    ├── settings/
       │         ├── dev.py
       │         ├── prod.py
       │    ├── urls.py
       │    └── utils/
       └── scripts/

目录结构调整后,apps中子应用的识别路径有了变化,因此,需要在配置文件中对导包路径进行调整:


BASE_DIR = Path(__file__).resolve().parent.parent

sys.path.insert(0, str( BASE_DIR / "apps") )

DEBUG = True

ALLOWED_HOSTS = ["*"]

8. git 初始化

在pcone文件夹下调出终端,通过终端执行以下操作:

cd ~/Desktop/pcone
git init

配置用户名和邮箱

git config user.name '你在远端git平台的用户名'
git config user.email '你在远端git平台的邮箱地址'

然后在你所选择的git平台,创建对应的远端git仓库,并根据平台的指南,完成ssh连接即可

Original: https://blog.csdn.net/sunnyliric/article/details/123478250
Author: xwu_2021
Title: 如何从零开始搭建基于Django的后端项目

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/327082/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

最近整理资源【免费获取】:   👉 程序员最新必读书单  | 👏 互联网各方向面试题下载 | ✌️计算机核心资源汇总