【Python可视化】matplotlib画图方法与技巧梳理,持续更新方便及时查阅

【Python可视化】matplotlib画图方法与技巧梳理,持续更新方便及时查阅

前言

  • 好久不见呀,朋友们,距离上一篇博文的发布已经过去了一年多了,眼看着今年2024也快过完了,然而今年一篇都没有发过,所以得赶紧出来 水一篇文章 认真写一篇文章才行了,也当作年终总结吧哈哈哈~
  • 这篇文章就记录整合一下我常用的Python画图方法与技巧,主要用的是matplotlib模块,如有新的也会及时更新,方便后续可以直接查阅~
  • 当然还有很多优秀的画图模块,但我觉得用什么模块画图取决于使用场景,比如注重交互性的话可以使用pyechart模块,而如果只需要静态的图形,则matplotlib已经足够,有时也会结合seaborn模块,像很多论文中所使用的图表就是如此~
  • 今天刚好是冬至,大家冬至快乐呀!另外,提前给大家拜年啦,2025元旦、2025蛇年行大运~

一、模块导入与全局配置

import os,warnings
os.makedirs('png',exist_ok=True)
warnings.filterwarnings('ignore')
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker # 这个主要用在将轴刻度改为百分比显示
import matplotlib.patches as mpatches
from matplotlib.legend_handler import HandlerPatch
from matplotlib.legend import _get_legend_handles_labels as get_legend_handles_labels

plt.style.use("default") # 先恢复默认
plt.style.use("ggplot") # 再设置主题
plt.rcParams["font.sans-serif"]=["SimHei"] # 设置字体
plt.rcParams["axes.unicode_minus"]=False # 该语句解决图像中的“-”负号的乱码问题
plt.rcParams['font.size'] = 12  # 字体大小

# 生成心形曲线的数据
t = np.linspace(0, 2 * np.pi, 1000)
love_x = 16 * np.sin(t) ** 3
love_y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)

np.random.seed(520)
love_data=np.random.randint(520,1314,size=4)
love_label=['L','O','V','E']

np.random.seed(520)
love_df=pd.DataFrame(np.random.uniform(520,1314,size=(10,4)),columns=love_label)

关于部分主题大致的使用场景如下:(plt.style.available能查看所有支持的主题名称)

主题名称 使用场景
ggplot 模仿 R 语言中 ggplot2 包的主题,适合数据科学和统计分析
fivethirtyeight 模仿 FiveThirtyEight 网站风格的主题,适合新闻和媒体报道
bmh 具有灰度背景和白色网格的主题,适合学术和科学研究
classic 经典的 matplotlib 主题,类似于 MATLAB 的默认样式
Solarize_Light2 一种明亮的主题,适合需要清晰视觉效果的场景

二、通用模板

模板一:单图
plt.figure(figsize=(10,5))
plt.plot(love_x,love_y,ls='--',marker='o',markersize=3,color='red',label='LOVE')
plt.legend()
plt.xlim(-30,30)
plt.ylim(-15,10)
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.axis('equal') # x,y轴比例一致
plt.title('LOVE',fontsize=15,color='red',backgroundcolor='white')
plt.tight_layout() # 这个一定要放在show和savefig之上
plt.savefig('png/单图.png') # 这个一定要放在show之上
plt.show()

模板二:单图(多y轴)
handles=[]
labels=[]
fig,ax=plt.subplots(nrows=1,ncols=1,figsize=(15,10))
for idx in range(4):
    if idx == 0:
        ax.plot(love_x,love_y,ls='--',marker='o',markersize=3,color=f'C{
     
     idx}',label='LOVE')
        ax.set_xlabel('x轴')
        ax.set_ylabel('y轴',color=f'C{
     
     idx}')
        ax.axis('equal') # x,y轴比例一致
        ax.tick_params('y', colors=f'C{
     
     idx}') # y轴颜色
        handles+=ax.get_legend_handles_labels()[0]
        labels+=ax.get_legend_handles_labels()[1]
    else:
        ax_twinx=ax.twinx()
        ax_twinx.plot(love_x*(idx+0.520),love_y*(idx+0.520),ls='--',marker='o',markersize=3,color=f'C{
     
     idx}',label=f'{
     
     idx} Times LOVE')
        ax_twinx.set_ylabel(f'y轴{
     
     idx}',color=f'C{
     
     idx}')
        ax_twinx.axis('equal') # x,y轴比例一致
        ax_twinx.tick_params('y', colors=f'C{
     
     idx}') # y轴颜色
        if idx >= 2:
            # 设置第三根以上Y轴位置,这里选择是右边
            ax_twinx.spines['right'].set_position(('outward', 60*(idx-1)))
        handles+=ax_twinx.get_legend_handles_labels()[0]
        labels+=ax_twinx.get_legend_handles_labels()[1]

# bbox_to_anchor=(左右,下上,左右,下上)
fig.legend(handles,labels,bbox_to_anchor=(0.3, 0.1, 0.1, 0.1))
plt.suptitle('LOVE',fontsize=20,color='red',backgroundcolor='white')
plt.tight_layout(rect=(0.14,0,0.97,0.98)) # 这个一定要放在show和savefig之上
plt.savefig('png/单图(多y轴).png') # 这个一定要放在show之上
plt.show()

模板三:多图
ls_list=['-',':','--','-.']
ncols=2
nrows=int(np.ceil(len(ls_list)/ncols))
fig,ax=plt.subplots(nrows=nrows,ncols=ncols,figsize=(20,5*nrows))
for idx,ls in enumerate(ls_list):
    x1=idx//ncols
    x2=idx%ncols

    ax[x1,x2].plot(love_x,love_y,ls=ls,color='red',label=f'ls = "${
     
     ls}$"')
    ax[x1,x2].legend()
    ax[x1,x2].set_xlim(-30,30)
    ax[x1,x2].set_ylim(-15,10)
    ax[x1,x2].set_xlabel('x轴')
    ax[x1,x2].set_ylabel('y轴')
    ax[x1,x2].axis('equal') # x,y轴比例一致

for idx in range(len(ls_list),ncols*nrows):
    x1=idx//ncols
    x2=idx%ncols
    fig.delaxes(ax[x1,x2])

plt.suptitle('LOVE',fontsize=20,color='red',backgroundcolor='white')
plt.tight_layout(rect=(0,0,0.97,0.98)) # 这个一定要放在show和savefig之上
plt.savefig('png/多图.png') # 这个一定要放在show之上
plt.show()

模板四:多图(不同比例)
def get_random_colors(num,seed=2024):
    # 随机颜色
    np.random.seed(seed)
    colors=[]
    colorArr = ['1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
    while len(colors) < num:
        color ="#"+''.join([np.random.choice(colorArr) for i in range(6)])
        if color not in colors:
            colors.append(color)
    return colors

ncols=3
nrows=2
colors=get_random_colors(4,seed=520)
plt.figure(figsize=(20,5*nrows))
for idx,color in enumerate(colors):
    x1=idx//ncols
    x2=idx%ncols

    if idx == 0:
        ax = plt.subplot2grid(shape=[nrows,ncols],loc=[idx,0],colspan=2)
    elif idx == 1:
        ax = plt.subplot2grid(shape=[nrows,ncols],loc=[0,2],rowspan=2)
    elif idx == 2:
        ax = plt.subplot2grid(shape=[nrows,ncols],loc=[1,0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值