import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import FuncFormatter
# 加载CSV文件
file_path = r'\\Mac\Home\Desktop\DATA\1.xls'
data = pd.read_excel(file_path)
# 设置全局字体为 Times New Roman
plt.rcParams['font.family'] = 'Times New Roman'
# 定义需要绘制的列和标签列
columns_to_plot = ['TN', 'TP', 'Turb', 'CODMn', 'DO','CODCr']
label_column = 'category'
# 定义简化的标签
simplified_labels = {
'TN': 'TN (mg/L)',
'TP': 'TP (mg/L)',
'Turb': 'Turb (NTU)',
'CODMn': 'COD$_{Mn}$ (mg/L)',
'DO': 'DO (mg/L)',
'CODCr': 'COD$_{Cr}$ (mg/L)'
}
# 设置绘图样式,背景为灰色,网格线为白色
sns.set(style="darkgrid") # 背景为灰色,网格线为白色
# palette = ["#5CB85C", "#337AB7", "#F0AD4E", "#D9534F", "#f7ec44", "#979797"]
palette = ["#25B5B5", "#C6E8E9", "#FAD2CA", "#F0756D"]
# 创建图形对象并设置大小
fig = plt.figure(figsize=(20, 15))
# 对每一列数据进行循环,生成子图
for i, column in enumerate(columns_to_plot, 1):
ax = plt.subplot(2, 3, i) # 创建子图位置
# 创建小提琴图
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
# 设置每个小提琴图的标题为当前列的简化标签
plt.title(simplified_labels[column], fontsize=26, loc='center', fontweight='bold')
if i <= 3:
ax.set_xticklabels([])
else:
plt.xticks(fontsize=26, fontweight='bold')
plt.ylabel('', fontsize=26, fontweight='bold')
plt.xlabel('', fontsize=26, fontweight='bold')
# 设置 X 和 Y 轴刻度字体大小
plt.xticks(fontsize=26, fontweight='bold')
plt.yticks(fontsize=26, fontweight='bold')
# 设置每个子图的边框为白色细线
ax.spines['top'].set_color('white')
ax.spines['bottom'].set_color('white') # 设置底边为白色
ax.spines['left'].set_color('white')
ax.spines['right'].set_color('white')
# 调整边框线条宽度
ax.spines['top'].set_linewidth(1)
ax.spines['bottom'].set_linewidth(1) # 设置底边的线宽
ax.spines['left'].set_linewidth(1)
ax.spines['right'].set_linewidth(1)
# 设置纵向和横向网格线
ax.grid(True, axis='y', color='white', linestyle='-', linewidth=0.5)
ax.grid(True, axis='x', color='white', linestyle='-', linewidth=0.5)
# 设置 Y 轴刻度为 5 个划分,去掉第一个刻度
y_min, y_max = ax.get_ylim()
y_ticks = [y_min + (y_max - y_min) * i / 5 for i in range(6)] # 创建 5 个 Y 轴刻度
y_ticks = y_ticks[1:] # 去掉第一个刻度
plt.yticks(y_ticks) # 设置 Y 轴刻度
# 根据不同的列选择不同的格式化方式
if column in ['TN', 'Turb', 'DO', 'CODCr']:
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, _: f'{int(x)}')) # 整数格式
elif column == 'CODMn':
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, _: f'{x:.1f}')) # 保留一位小数
else:
ax.yaxis.set_major_formatter(FuncFormatter(lambda x, _: f'{x:.2f}')) # 保留两位小数
# 如果当前列是 'TN',则在图中添加红色虚线,并标注 'IV'
if column == 'TN':
# 手动设置 Y 轴范围
ax.set_ylim(0, 7.5)
# 设置整数刻度
ax.yaxis.set_major_locator(plt.MultipleLocator(2))
# 添加 y=3 的红色虚线\
ax.axhline(y=1, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 0.4, 'III', color='red', fontsize=24, ha='center',fontweight='bold') # fontweight='bold',
ax.text(0.5, 1.1, 'IV', color='red', fontsize=24, ha='center', fontweight='bold')
ax.axhline(y=1.5, color='red', linestyle='--', linewidth=2)
ax.axhline(y=2, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 1.6, 'V', color='red', fontsize=24, ha='center',fontweight='bold')#fontweight='bold',
ax.text(0.5, 2.3, 'VI', color='red', fontsize=24, ha='center',fontweight='bold')
if column == 'TP':
# 手动设置 Y 轴范围
ax.set_ylim(0.02, 0.18)
# 设置整数刻度
ax.yaxis.set_major_locator(plt.MultipleLocator(0.04))
# 添加 y=3 的红色虚线
ax.axhline(y=0.1, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 0.08, 'II', color='red', fontsize=26, ha='center',fontweight='bold')
ax.text(0.5, 0.12, 'III', color='red', fontsize=26, ha='center',fontweight='bold')
if column == 'Turb':
# 手动设置 Y 轴范围
ax.set_ylim(0, 95)
# 设置整数刻度
ax.yaxis.set_major_locator(plt.MultipleLocator(20))
# 添加 y=3 的红色虚线
ax.axhline(y=15, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 5, 'I', color='red', fontsize=26, ha='center',fontweight='bold')
ax.axhline(y=25, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 18, 'II', color='red', fontsize=26, ha='center',fontweight='bold')
ax.text(0.5, 30, 'III', color='red', fontsize=24, ha='center',fontweight='bold')
ax.axhline(y=40, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 60, 'IV', color='red', fontsize=24, ha='center',fontweight='bold')
ax.axhline(y=80, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 90, 'V', color='red', fontsize=24, ha='center',fontweight='bold')
if column == 'CODMn':
# 手动设置 Y 轴范围
ax.set_ylim(1.2, 3.8)
# 设置整数刻度
ax.yaxis.set_major_locator(plt.MultipleLocator(0.6))
# 添加 y=3 的红色虚线
ax.axhline(y=2, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 1.7, 'I', color='red', fontsize=24, ha='center',fontweight='bold')
ax.text(0.5, 2.3, 'II', color='red', fontsize=24, ha='center',fontweight='bold')
if column == 'DO':
# 手动设置 Y 轴范围
ax.set_ylim(4.2, 8.5)
# 设置整数刻度
ax.yaxis.set_major_locator(plt.MultipleLocator(1))
# 添加 y=3 的红色虚线
ax.axhline(y=7.5, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 8, 'I', color='red', fontsize=24, ha='center',fontweight='bold')
ax.axhline(y=6, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 6.7, 'II', color='red', fontsize=24, ha='center',fontweight='bold')
ax.axhline(y=5, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 5.4, 'III', color='red', fontsize=24, ha='center',fontweight='bold')
ax.text(0.5, 4.4, 'IV', color='red', fontsize=24,ha='center',fontweight='bold')
if column == 'CODCr':
# 手动设置 Y 轴范围
ax.set_ylim(4, 17)
# 设置整数刻度
ax.yaxis.set_major_locator(plt.MultipleLocator(3))
# 添加 y=3 的红色虚线
ax.axhline(y=15, color='red', linestyle='--', linewidth=2)
ax.text(0.5, 13, 'I', color='red', fontsize=24, ha='center',fontweight='bold')
ax.text(0.5, 16, 'II', color='red', fontsize=24,ha='center',fontweight='bold')
# 添加全局的 X 和 Y 轴标签
fig.supxlabel('Cluster', fontsize=28, fontweight='bold')
fig.supylabel('Value', fontsize=28, fontweight='bold')
# 调整布局并增加上下的间距
plt.tight_layout(rect=[0, 0, 1, 0.96]) # 为全局标签留出空间
plt.subplots_adjust(hspace=0.1) # 增加上下的间距,可以根据需要调整
# 保存图片
output_path = r'\\Mac\Home\Desktop\DATA\小提琴聚类图-分级.jpg' # 指定输出文件名
plt.savefig(output_path, dpi=300, bbox_inches='tight') # 以高分辨率保存图片
output_path2 = r'\\Mac\Home\Desktop\DATA\小提琴聚类图-分级.svg' # 指定输出文件名
plt.savefig(output_path2, dpi=300, bbox_inches='tight') # 以高分辨率保存图片
plt.show()
print(f"小提琴图已保存为: {output_path}")这是源代码帮我修改C:\Python312\python.exe \\Mac\Home\Desktop\箱型图-标记线_副本2.py
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: FutureWarning:
Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0. Assign the `x` variable to `hue` and set `legend=False` for the same effect.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: UserWarning: The palette list has more values (4) than needed (1), which may not be intended.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: FutureWarning:
Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0. Assign the `x` variable to `hue` and set `legend=False` for the same effect.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: UserWarning: The palette list has more values (4) than needed (1), which may not be intended.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: FutureWarning:
Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0. Assign the `x` variable to `hue` and set `legend=False` for the same effect.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: UserWarning: The palette list has more values (4) than needed (1), which may not be intended.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: FutureWarning:
Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0. Assign the `x` variable to `hue` and set `legend=False` for the same effect.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: UserWarning: The palette list has more values (4) than needed (1), which may not be intended.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: FutureWarning:
Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0. Assign the `x` variable to `hue` and set `legend=False` for the same effect.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: UserWarning: The palette list has more values (4) than needed (1), which may not be intended.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: FutureWarning:
Passing `palette` without assigning `hue` is deprecated and will be removed in v0.14.0. Assign the `x` variable to `hue` and set `legend=False` for the same effect.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
\\Mac\Home\Desktop\箱型图-标记线_副本2.py:39: UserWarning: The palette list has more values (4) than needed (1), which may not be intended.
sns.violinplot(data=data, x=label_column, y=column, palette=palette)
Traceback (most recent call last):
File "\\Mac\Home\Desktop\箱型图-标记线_副本2.py", line 175, in <module>
plt.show()
File "C:\Python312\Lib\site-packages\matplotlib\pyplot.py", line 614, in show
return _get_backend_mod().show(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\JetBrains\PyCharm 2024.1.6\plugins\python\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 41, in __call__
manager.show(**kwargs)
File "C:\Program Files\JetBrains\PyCharm 2024.1.6\plugins\python\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 144, in show
self.canvas.show()
File "C:\Program Files\JetBrains\PyCharm 2024.1.6\plugins\python\helpers\pycharm_matplotlib_backend\backend_interagg.py", line 85, in show
buffer = self.tostring_rgb()
^^^^^^^^^^^^^^^^^
AttributeError: 'FigureCanvasInterAgg' object has no attribute 'tostring_rgb'. Did you mean: 'tostring_argb'?
Process finished with exit code 1
最新发布