import pandas as pd import matplotlib.pyplot as plt import matplotlib…
- User
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())
定义表头名称(根据实际情况调整)
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 = ax1.twinx()
绘制洪水发生频次的折线图(右边纵轴)
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²” 中的 “2” 没有上标,这是因为在 Matplotlib 中,如果你直接写
'Area (km2)',数字2是普通字符,不会自动变为上标。✅ 解决方法:
将
'Area (km2)'改为使用 Unicode 上标字符或者 LaTeX 格式(取决于是否启用了 LaTeX 渲染)。对于简单的上标,推荐使用 Unicode 上标字符,因为不需要额外配置。🛠 修改方式如下:
把这一行:
ax2.set_ylabel('Area (km2)', color='#d62728')改为:
ax2.set_ylabel('Area (km²)', color='#d62728')⚠️ 注意:这里是
km²,其中²是数字 2 的上标 Unicode 字符(U+00B2)。
✅ 更通用的方法(如果想在更多场合支持上标)
你也可以使用 Matplotlib 的数学文本模式(LaTeX 风格),但需要确保
text.usetex设置为 True(默认通常是 False,且需要系统安装 LaTeX)。简单示例:ax2.set_ylabel('Area (km$^2$)', color='#d62728')⚠️ 但这种方法在未启用 LaTeX 时可能不渲染或报错,所以更推荐用 Unicode。
✅ 推荐做法(简洁、跨平台):
ax2.set_ylabel('Area (km²)', color='#d62728')这样就可以完美显示 “km²” 中的上标 2 了。
如需进一步美化图表,例如调整字体大小、添加网格线、调整图例位置等,我也可以继续帮你优化。需要的话告诉我 😊
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.