import pandas as pd import matplotlib.pyplot as plt import… · The Chat Archiveimport pandas as pd import matplotlib.pyplot as plt import matplotlib…
Download ▾
From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with
hunyuan-turbos-20250416’s answer.import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
读取 Excel 文件,表单2
file_path = 'Pakistan Rice.xlsx' # 替换为你的 Excel 文件路径
data = pd.read_excel(file_path, sheet_name=0)
打印表头,检查列名
print("Excel 文件的表头:", data.columns.tolist())
定义表头名称(根据实际情况调整)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
year_column = 'Year' # 年份列名
frequency_column = 'Area' # 洪水发生频次列名
casualties_column = 'Yield' # 伤亡人数列名
检查表头
for col in [year_column, frequency_column, casualties_column]:
if col not in data.columns:
raise KeyError(f"列 '{col}' 在 Excel 文件中不存在,请检查表头名称。")
提取表头数据
years = data[year_column] # 年份
frequency = data[frequency_column] # 洪水发生频次
casualties = data[casualties_column] # 伤亡人数
创建图表和第一个坐标轴(左边纵轴)
fig, ax1 = plt.subplots(figsize=(10, 6))
绘制伤亡人数的折线图(左边纵轴)
ax1.plot(years, casualties, color='#1f77b4', linestyle='-', marker='o', label='Yield') # 蓝色折线图
ax1.set_xlabel('Year') # 横轴标签
ax1.set_ylabel('Yield', color='#1f77b4') # 左边纵轴标签
ax1.tick_params(axis='y', labelcolor='#1f77b4') # 左边纵轴刻度颜色
为伤亡人数添加趋势线(左边纵轴)
z1 = np.polyfit(years, casualties, 1) # 线性拟合(1 表示一阶多项式,即直线)
p1 = np.poly1d(z1) # 生成趋势线函数
ax1.plot(years, p1(years), color='#1f77b4', linestyle='--', label='Trends in Production') # 虚线趋势线
创建第二个坐标轴(右边纵轴),共享横轴
绘制洪水发生频次的折线图(右边纵轴)
ax2.plot(years, frequency, color='#d62728', linestyle='-', marker='s', label='Area') # 红色折线图
ax2.set_ylabel('Area', color='#d62728') # 右边纵轴标签
ax2.tick_params(axis='y', labelcolor='#d62728') # 右边纵轴刻度颜色
为洪水发生频次添加趋势线(右边纵轴)
z2 = np.polyfit(years, frequency, 1) # 线性拟合
p2 = np.poly1d(z2) # 生成趋势线函数
ax2.plot(years, p2(years), color='#d62728', linestyle='--', label='Trends in Planted Area') # 虚线趋势线
添加单位
plt.rcParams['font.sans-serif'] = ['SimHei'] # 使用黑体支持中文
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
ax1.set_xlabel('Year')
ax1.set_ylabel('Weight (1000t)', color='#1f77b4')
ax2.set_ylabel('Area (km2)', color='#d62728')
添加标题
plt.title('Rice Area and Production in Pakistan From 1961 to 2023')
添加图例
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')
fig.tight_layout()
plt.show()
这是我写的巴基斯坦大米产量和种植面积图,但是右侧Y轴的平方千米中2没有上表,请帮我优化一下。
Assistant
你做得已经很棒了!下面我们来解决你提到的 “右侧 Y 轴上 ‘km²’ 中的 ² 没有上标” 的问题。
🛠 原因:
在 Matplotlib 中,普通字符串并不能自动识别数学符号(如上标的 ²)。要显示数学表达式(比如平方、希腊字母等),应使用 LaTeX 语法(在字符串前后加上 $)。
✅ 解决方案:
我们将 ax2.set_ylabel('Area (km2)', ...) 中的 'km2' 改为 '$km^2$',这样 ² 就能正常以上标形式显示了。
✅ 你应该修改的地方如下:
# 替换这行:
# ax2.set_ylabel('Area (km2)', color='#d62728')
# 改为这行:
ax2.set_ylabel('Area ($km^2$)', color='#d62728')
如果你希望字体支持中文,又要兼容数学表达式,使用如下方式更稳妥:
ax2.set_ylabel(r'Area ($km^2$)', color='#d62728') # 加了 raw string 处理 LaTeX 表达更安全
✅ 最终效果:
图右侧 Y 轴标签将显示为:
Area (km²)
其中 ² 正确为上标。
✅ 全部优化代码参考(仅展示修改部分):
# 添加单位部分
plt.rcParams['font.sans-serif'] = ['SimHei'] # 支持中文黑体
plt.rcParams['axes.unicode_minus'] = False # 解决负号问题
ax1.set_xlabel('Year')
ax1.set_ylabel('Weight (1000t)', color='#1f77b4')
ax2.set_ylabel(r'Area ($km^2$)', color='#d62728') # ✅ 用 LaTeX 显示平方公里
✅ 加分小建议(可选):
-
让趋势线颜色略淡一些:提升可读性
ax1.plot(years, p1(years), color='#1f77b4', linestyle='--', alpha=0.6, label='Trends in Production')
同样的在 ax2 用 alpha=0.6。
-
年份排序(若有问题)
data.sort_values(by=year_column, inplace=True)
如果还有别的图表美化需求,比如中文标题、图例位置优化、保存图片为高清PNG等,也可以告诉我 😊