面试题答案
一键面试import pandas as pd
import matplotlib.pyplot as plt
# 读取气温数据
temp_df = pd.read_csv('temperature.csv')
# 读取降水量数据
precipitation_df = pd.read_csv('precipitation.csv')
# 合并数据,假设两个文件通过城市和月份匹配
merged_df = pd.merge(temp_df, precipitation_df, on=['city','month'])
# 创建双Y轴图表
fig, ax1 = plt.subplots()
# 绘制气温曲线
ax1.plot(merged_df['month'], merged_df['temperature'], 'b-', label='Temperature')
ax1.set_xlabel('Month')
ax1.set_ylabel('Temperature (°C)', color='b')
ax1.tick_params('y', colors='b')
# 创建第二个Y轴
ax2 = ax1.twinx()
# 绘制降水量曲线
ax2.plot(merged_df['month'], merged_df['precipitation'], 'r-', label='Precipitation')
ax2.set_ylabel('Precipitation (mm)', color='r')
ax2.tick_params('y', colors='r')
# 添加图例
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='best')
# 设置图表标题
plt.title('Temperature and Precipitation Trends')
# 显示图表
plt.show()
假设temperature.csv
文件包含city
、month
、temperature
列,precipitation.csv
文件包含city
、month
、precipitation
列。以上代码实现了:
- 使用
pandas
读取两个CSV文件。 - 根据城市和月份合并两个数据框。
- 使用
matplotlib
创建双Y轴图表,分别绘制气温和降水量随月份的变化曲线,并添加坐标轴标注和图例。