matplotlib绘制折线图的基本配置(万能模板案例)
作者:王小王-123 时间:2022-09-06 18:06:17
前面我们已经构造了一种图形可视化的模板了,下面我们直接使用这个模板进行增添和修改,进一步的改善图形的外观。
import matplotlib.pyplot as plt
# 画布
plt.figure(figsize=(9,3), # (宽度 , 高度) 单位inch
dpi=100, # 清晰度 dot-per-inch
facecolor='#CCCCCC', # 画布底色
edgecolor='black',linewidth=0.2,frameon=True, # 画布边框
#frameon=False # 不要画布边框
)
# ax = plt.gca()
# ax.plot()
plt.plot()
plt.show()
设置好基本的图形之后,我们就可以向上面添加一些数据了
(图例放置位置)
"""legend( handles=(line1, line2, line3),
labels=('label1', 'label2', 'label3'),
'upper right')
The *loc* location codes are::
'best' : 0, (currently not supported for figure legends)
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10,"""
折线图案例
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 画布
plt.figure(figsize=(15,5), # (宽度 , 高度) 单位inch
dpi=100, # 清晰度 dot-per-inch
facecolor='#CCCCCC', # 画布底色
edgecolor='black',linewidth=0.2,frameon=True, # 画布边框
#frameon=False # 不要画布边框
)
# 数据
x = np.linspace(0, 2 * np.pi, 50)
y1 = np.sin(x)
y2 = np.cos(x)
df = pd.DataFrame([x,y1,y2]).T
df.columns = ['x','sin(x)','cos(x)']
# 图形
plt.plot(df['x'],df['sin(x)'],label='sin(x)')
plt.plot(df['x'],df['cos(x)'],label='cos(x)')
# 图例
plt.legend(loc='lower right') # 不带参数的时候,使用图形的label属性
# plt.legend(labels=['sin','cos'])
# 标题
#plt.title("sin(x) and cos(x)",loc='center',y=0.85)
# 字体字典
font_dict = {'fontsize': 12, 'fontweight': 'bold', 'color': 'green'}
plt.title("sin(x) and cos(x)",loc='center',y=0.9, fontdict=font_dict)
查看全局参数
# matplotlib.pyplot的全局参数
plt.rcParams
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 设置中文字体
plt.rcParams['axes.unicode_minus'] = False # 不使用中文减号
plt.rcParams['font.sans-serif'] = 'FangSong' # 设置字体为仿宋(FangSong)
# 画布
plt.figure(figsize=(15,5), # (宽度 , 高度) 单位inch
dpi=120, # 清晰度 dot-per-inch
facecolor='#CCCCCC', # 画布底色
edgecolor='black',linewidth=0.2,frameon=True, # 画布边框
#frameon=False # 不要画布边框
)
# 数据
x = np.linspace(0, 2 * np.pi, 50)
y1 = np.sin(x)
y2 = np.cos(x)
df = pd.DataFrame([x,y1,y2]).T
df.columns = ['x','sin(x)','cos(x)']
# 图形
plt.plot(df['x'],df['sin(x)'],label='sin(x)')
plt.plot(df['x'],df['cos(x)'],label='cos(x)')
# 图例
plt.legend()
# 标题
#plt.title("sin(x) and cos(x)",loc='center',y=0.85)
# 字体字典
font_dict = {'fontsize': 10, 'fontweight': 'bold', 'color': 'grey'}
# 中文标题, 默认的字体不支持中文
plt.title("三角函数:正弦和余弦",loc='center',y=0.9, fontdict=font_dict)
改变字体
# 字体字典
font_dict = {'fontsize': 10, 'fontweight': 'bold', 'color': 'grey'}
# 中文标题, 默认的字体不支持中文
plt.title("三角函数:正弦和余弦",loc='center',y=0.9, fontdict=font_dict)
添加X轴和Y轴
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# 画布
plt.figure(figsize=(15,5), # (宽度 , 高度) 单位inch
dpi=120, # 清晰度 dot-per-inch
facecolor='#CCCCCC', # 画布底色
edgecolor='black',linewidth=0.2,frameon=True, # 画布边框
#frameon=False # 不要画布边框
)
# 数据
x = np.linspace(0, 2 * np.pi, 50) #
y1 = np.sin(x)
y2 = np.cos(x)
df = pd.DataFrame([x,y1,y2]).T
df.columns = ['x','sin(x)','cos(x)']
# 标题
#plt.title("sin(x) and cos(x)",loc='center',y=0.85)
# 字体字典
font_dict = {'fontsize': 10, 'fontweight': 'bold', 'color': 'black','fontfamily':'KaiTi'}
# 设置全局中文字体
plt.rcParams['font.sans-serif'] = 'KaiTi' # 设置全局字体为中文 楷体
plt.rcParams['axes.unicode_minus'] = False # 不使用中文减号
# 常用中文字体
# 宋体 SimSun
# 黑体 SimHei
# 微软雅黑 Microsoft YaHei
# 微软正黑体 Microsoft JhengHei
# 新宋体 NSimSun
# 新细明体 PMingLiU
# 细明体 MingLiU
# 标楷体 DFKai-SB
# 仿宋 FangSong
# 楷体 KaiTi
# 中文标题, 默认的字体不支持中文
plt.title("三角函数:正弦和余弦",loc='center',y=1, fontdict=font_dict)
# Axes 坐标系设置
ax = plt.gca() # 获取当前坐标系
ax.set_facecolor('#FEFEFE') # 设置坐标系参数。。。。
#plt.xlabel() => ax.set_xlabel()
# ax.set_facecolor('#EE2211')
# ax.set_alpha(0.15)
# plt.title() => ax.set_title("AX TITLE")
# X轴标签
plt.xlabel("X轴") # loc: 左中右 left-center-right
# Y轴标签
plt.ylabel("Y轴") # loc: 上中下 top-center-bottom
# X轴范围
plt.xlim(0,np.pi) # 只显示X在0-Pi之间的部分
# Y轴范围
plt.ylim([0,1.1]) # 只显示Y在0-1之间的部分
# X轴刻度
xticks = np.array([0,1/4,2/4,3/4,1]) * np.pi # X 轴上刻度的值
labels = ["0",'1/4 Π','1/2 Π','3/4 Π', 'Π'] # X 轴上刻度标签
plt.xticks(xticks, labels) # 如果没有传入labels,直接使用ticks作为labels
# Y轴刻度
yticks = np.arange(0.0,1.2,0.2) # X 轴上刻度的值
plt.yticks(yticks) # 如果没有传入labels,直接使用ticks作为labels
# 根据刻度画网格线
#plt.grid()
plt.grid(axis='x') # axis: both, x, y 在哪个轴上画格子
# 图形
plt.plot(df['x'],df['sin(x)'],label='sin(x)')
plt.plot(df['x'],df['cos(x)'],label='cos(x)')
# 图例
plt.legend()
# plt.legend(labels=['sin','cos'])
折线图绘制万能模板
# 处理数据
df = pd.read_csv(r'unemployment-rate-1948-2010.csv',usecols=['Year','Period','Value'])
df.replace('^M','-',regex=True, inplace=True)
df['year_month'] = df['Year'].astype('U') + df['Period']
# 设置画布和参数
plt.figure(figsize=(16,4), dpi=130, facecolor='white', edgecolor='black', frameon=True)# 画布底色
# 添加数据
plt.plot(df['year_month'], df['Value'],'c')#改变颜色和线条
'''
一般不需要改动下面的,只需要设置一些固定常量
'''
# 构造X轴标签,一般不用设置
xticks = [df['year_month'][i] for i in np.arange(0,df['year_month'].size,15)]#X轴的显示
#X轴设置倾斜度,可以解决标签过长的问题,大小可以设置默认
plt.xticks(xticks,rotation=100,size=10)
# 设置图形上的各类主题值
plt.suptitle('主标题:unemployment-rate-1948-2010',size=17,y=1.0)
plt.title("绘制日期:2022年 昵称:王小王-123", loc='right',size=15,y=1)
plt.title("主页:https://blog.csdn.net/weixin_47723732", loc='left',size=12,y=1)
# 设置坐标轴上的字体标签
font_dict = {'fontsize': 15, 'fontweight': 'bold', 'color': 'black','fontfamily':'KaiTi'}
plt.xlabel('年月',font_dict)
plt.ylabel('失业率',font_dict)
来源:https://wxw-123.blog.csdn.net/article/details/123745340
标签:matplotlib,折线图
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python如何编写win程序
2022-12-09 11:48:38
![](https://img.aspxhome.com/file/2023/6/76856_0s.png)
回顾Javascript React基础
2023-07-13 00:57:00
python函数指定默认值的实例讲解
2021-07-20 14:05:01
Python实现基于PIL和tesseract的验证码识别功能示例
2022-10-22 23:09:54
![](https://img.aspxhome.com/file/2023/4/94174_0s.png)
常用Oracle分析函数大全
2023-07-03 08:16:14
![](https://img.aspxhome.com/file/2023/0/63710_0s.jpg)
百度、谷歌和雅虎的近日LOGO
2008-05-19 12:11:00
![](https://img.aspxhome.com/file/UploadPic/20085/19/2008519122037724s.gif)
Python 中 function(#) (X)格式 和 (#)在Python3.*中的注意事项
2021-11-15 18:53:31
GDAL 矢量属性数据修改方式(python)
2021-01-30 20:53:28
![](https://img.aspxhome.com/file/2023/7/78537_0s.jpg)
关于Django框架的关系模型序列化和一对多关系中的序列化解析
2023-01-15 00:52:53
![](https://img.aspxhome.com/file/2023/1/79531_0s.jpg)
如何判断URL格式是否符合规范?
2010-01-12 20:14:00
CSS3中的box-sizing属性
2010-04-05 21:52:00
![](https://img.aspxhome.com/file/UploadPic/20104/5/20090424070002186-44s.png)
用python记录运行pid,并在需要时kill掉它们的实例
2023-07-31 17:30:18
Python实现根据Excel生成Model和数据导入脚本
2022-01-10 09:58:12
解决使用export_graphviz可视化树报错的问题
2022-06-10 18:35:59
![](https://img.aspxhome.com/file/2023/2/84902_0s.jpg)
asp实现将人民币数字改为大写
2008-05-21 14:08:00
微信小程序上传图片到php服务器的方法
2023-11-07 11:57:25
OpenCV图像分割之分水岭算法与图像金字塔算法详解
2022-11-27 07:59:24
![](https://img.aspxhome.com/file/2023/0/97640_0s.jpg)
Python画图时如何调用本地字体
2023-08-02 08:51:31
![](https://img.aspxhome.com/file/2023/6/61486_0s.png)
python脚本框架webpy入门安装及应用创建
2023-08-23 05:08:51
一文详解Go语言fmt标准库的常用占位符使用
2023-08-07 01:57:56