我在使用python绘图时,想要这样绘图:每个组的所有数据放到一起,然后不同组进行比较。
类似这样的图。
然后 我搞了挺长时间,搞了一个类似的图,需要计算每个柱子的位置。
gpt提示词可以这样写:
把所有颜色相同的柱子放在一起。每个套件的柱放在一起,并且中间没有间隙。不同套件的柱子之间有间隙。请你使用python画图。(定义宽度,并把每个柱子放在合适的位置)。
然后该柱子宽度,高度,颜色。可以制作出类似的图。
代码如下:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np# 提供的数据
data = {"Suite": ["FP_rate"] * 13 + ["FP_speed"] * 10 + ["Int_rate"] * 10 + ["Int_speed"] * 10,"Fitting Time": [0.9217, 0.8048, 0.7858, 0.8889, 0.7595, 0.7906, 0.7962, 0.7631, 0.7737, 0.8022, 0.7901, 0.8909,0.9123,0.6051, 0.5374, 0.5738, 0.5725, 0.5567, 0.5768, 0.5345, 0.5276, 0.5917, 0.5639,0.7211, 0.6849, 0.6662, 0.6629, 0.6621, 0.6723, 0.6752, 0.6849, 0.6950, 0.6580,0.5896, 0.6512, 0.6412, 0.5862, 0.6272, 0.6005, 0.6045, 0.6392, 0.6163, 0.5715],"MAE": [8.7349, 5.2842, 3.6923, 2.9271, 5.3044, 2.0670, 4.1021, 5.6323, 5.4719, 12.4079, 7.0451, 2.8996, 2.1564,8.8819, 2.8309, 1.7067, 2.4580, 2.3036, 1.4780, 3.6271, 4.7245, 1.4008, 6.2279,2.6752, 3.6861, 4.5846, 2.7546, 4.2150, 6.6735, 2.6371, 2.6476, 7.7664, 2.5001,0.0334, 0.0904, 0.0952, 0.1381, 0.0767, 0.0816, 0.0281, 0.0152, 0.0776, 0.2814],"Prediction Time": [0.0130, 0.0132, 0.0147, 0.0128, 0.0128, 0.0132, 0.0127, 0.0128, 0.0129, 0.0176, 0.0169, 0.0253,0.0155,0.0134, 0.0130, 0.0219, 0.0123, 0.0117, 0.0134, 0.0115, 0.0121, 0.0124, 0.0114,0.0141, 0.0163, 0.0133, 0.0136, 0.0132, 0.0152, 0.0135, 0.0158, 0.0151, 0.0234,0.0125, 0.0130, 0.0119, 0.0145, 0.0127, 0.0120, 0.0118, 0.0152, 0.0116, 0.0142]
}# 创建DataFrame
df = pd.DataFrame(data)# 总宽度分配给每组的部分
total_width_per_group = 1.0# 单个柱子的宽度(考虑到每个套件内部留有小间隙)
individual_bar_width = total_width_per_group / (len(df['Suite'].unique()) * len(df) // len(df['Suite'].unique())) * 0.93# 每个套件组内部的间隙宽度
internal_gap = 0.07 * individual_bar_width# 每个套件组的总宽度
group_total_width = 0.05+(len(df) // len(df['Suite'].unique())) * individual_bar_width + ((len(df) // len(df['Suite'].unique())) - 1) * internal_gap# 计算每个套件的基准位置
num_groups = len(df['Suite'].unique())
group_base_positions = np.linspace(0, num_groups - 1, num_groups) * (group_total_width + 1.5 * individual_bar_width)# 绘制图表
fig, axes = plt.subplots(1, 3, figsize=(30, 3), dpi=100)# Colors for different suites
colors = {'FP_rate': '#FDA629', 'FP_speed': '#CA446A', 'Int_rate': '#05C5A8', 'Int_speed': '#8A7093'}for ax, metric in zip(axes, ['Fitting Time', 'MAE', 'Prediction Time']):for suite_index, suite in enumerate(sorted(df['Suite'].unique())):# 获取当前套件的数据suite_data = df[df['Suite'] == suite].reset_index()for bar_index in range(len(suite_data)):# 计算每个柱子的位置bar_position = group_base_positions[suite_index] + bar_index * (individual_bar_width + internal_gap)# 绘制柱子ax.bar(bar_position, suite_data.loc[bar_index, metric], color=colors[suite], width=individual_bar_width)ax.set_title(metric)# 设置X轴刻度标签
for ax in axes:ax.set_xticks(group_base_positions + group_total_width / 2 - individual_bar_width / 2)ax.set_xticklabels(sorted(df['Suite'].unique()))plt.tight_layout()
plt.show()