plt模板

一、背景

plt画的图不好看,需要好多地方自己设置。干脆设置一个末班。

 

 

二、准备工作

2.1 数据准备

 

 

X、Y、Size=RAND() 都是随机数。

 

 

2.2 字体准备

可以在网上下载一下自己需要的字体。

 

 

 

 

 

三、代码展示

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
from adjustText import adjust_text
import matplotlib.font_manager as fm
import warnings
warnings.filterwarnings('ignore')


# 保证中文能够显示
plt.rcParams["font.family"]="SimHei"

# 设置默认字体
plt.rcParams['font.sans-serif'] = 'Cambria'
# print(plt.rcParams['font.sans-serif'])

# 导入字体
title_font_path = r'E:\font\Roboto\Roboto\Roboto-Bold.ttf'
# 2. 使用 FontProperties 类加载字体文件
custom_font = fm.FontProperties(fname=title_font_path)  # 这个字体主要用于标题



# 数据准备
path_file = r'Figure.xlsx'
df = pd.read_excel(path_file, sheet_name='Sheet1')

#  字体大小
fontsize_dict = {'ticks_fontsize':10, 'label_fontsize':10, 'text_fontsize':10, 'title_fontsize':20}


# text与label的偏移距离
df['offset_X'] = 0.0001
df['offset_Y'] = 0.0001

# 当散点图的label相互遮掩的时候,可以用这段代码,进行数据的准备
a = df[df['Name']=='abcd_1'].index.tolist()
df['offset_X'][a] = -0.025
df['offset_Y'][a] = -0.025

# print(df)

sizes = df['Size']*1000
names = df['Name']
colors = df['HEX']




X = df['X']
Y1 = df['Y']
Y2 = 0.21*X+0.5
Y3 = 0.35*X+0.1


Regions = df['Group'].unique()
Regions_dict={}
for Region in Regions:
    Regions_dict[Region] = df[df['Group'] == Region].index.to_list()


length = 16
width = 9
fig=plt.figure(num=1, figsize=(length, width)) #facecolor='#e8eff4' 可以设置背景色
ax=fig.add_subplot(111)
ax.set_facecolor('#e8eff4')  # 设置subplot背景色,如果subplot与figure需要不同的的背景色时进行设置


# 设置subplot与figure的页边距
margin_x = length*0.005
margin_y = width*0.005
plt.subplots_adjust(left=margin_x, right=1-margin_x, top=1-margin_y, bottom=margin_y)


# 绘图
for Region in Regions:
     index  =  Regions_dict[Region]
     Region = ax.scatter(X[index], Y1[index], c=colors[index], s=sizes[index], label=Region)
y2 = ax.plot(X, Y2, color = 'r', linewidth=0.5, label='Y2 = 0.21*X+0.5')
y3 = ax.plot(X, Y3, color = 'g', linewidth=0.5, label='Y3 = 0.35*X+0.1')
# for i in range(len(X)):
#     plt.annotate(label[i], xy=(X[i], Y1[i]), xytext=(X[i] , Y1[i] ))




# 设置轴是否显示
ax.spines["top"].set_visible(False)#上轴不显示
ax.spines["right"].set_visible(False)#
ax.spines["left"].set_visible(False)#
# ax.spines["bottom"].set_visible(False)#下

# 设置轴的线型
# 设置 X 轴的线型
# ax.spines['bottom'].set_linestyle('-')  # 设置底部轴线为虚线
# ax.spines['bottom'].set_color('blank')    # 设置底部轴线颜色为红色
ax.spines['bottom'].set_linewidth(0.3)    # 设置底部轴线宽度为2


# 修改轴字体大小
plt.xticks(fontsize=fontsize_dict['ticks_fontsize'])  # 设置fontsize参数调整X轴标签字体大小
plt.yticks(fontsize=fontsize_dict['ticks_fontsize'])  # 设置fontsize参数调整X轴标签字体大小
# 设置 Y 轴从 0 开始
ax.set_ylim(bottom=0)

# 设置 轴以百分比显示
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))  # xmax 设置最大值,decimals 设置小数位数
ax.xaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))  # xmax 设置最大值,decimals 设置小数位数

# 设置网格线
# ax.grid(True, which='both', linestyle='--', linewidth=0.5, color='gray')

#设置刻度线
# ax.tick_params(left=False,  direction="out",length=2,width=1, color="black")
ax.tick_params(left=True, bottom=True,   direction="out", length=2, width=0.5, color="black")
# ax.tick_params("x",labelrotation=10)#类标旋转

# 添加轴坐标标签,表头,图例
ax.set_xlabel("X轴标题", fontsize=fontsize_dict['label_fontsize']) #添加x轴坐标标签,后面看来没必要会删除它,这里只是为了演示一下。
ax.set_ylabel("Y轴标题", fontsize=fontsize_dict['label_fontsize']) #添加y轴标签,设置字体大小为16,这里也可以设字体样式与颜色
ax.set_title("title标题", fontsize=fontsize_dict['title_fontsize'], fontproperties=custom_font, c='r') #标题(表头)


# 获取子图的句柄和标签,从而对legend进行重新排序布局
handles, labels = ax.get_legend_handles_labels()
legend_order = [0, 3, 1, 4, 2]
handles = [handles[i] for i in legend_order]
labels = [labels[i] for i in legend_order]
legend = ax.legend(handles=handles, labels=labels, loc='upper center',  ncol=len(Regions),
                   handletextpad=0.5, handlelength=0.5, frameon=True)   # frameon=空值图例边框、背景是否显示
for handle in legend.legendHandles:
    try:
        handle.set_sizes([80])  # 设置图例中标记的大小
    except Exception:
        continue


# 标注每个点
offsets = list(zip(df['offset_X'],df['offset_Y']))
for i, name in enumerate(names):
    plt.text(X[i] + offsets[i][0], Y1[i] + offsets[i][1], name, fontsize=fontsize_dict['text_fontsize'])
    # plt.text(name)
    # print(name)


plt.savefig('text.svg', format='svg')
plt.savefig('text.png', dpi=800)

plt.show()

 

四、结果展示

 

 

  • 注意标题是有乱码的,那些是中文,我上传的字体,只能用与英语,而不能用于汉语

 

posted @ 2025-03-10 11:01  qsl_你猜  阅读(13)  评论(0)    收藏  举报