MST

星途 面试题库

面试题:Python利用Pandas和Matplotlib实现多数据关联可视化

现有两个CSV文件,一个记录了不同城市每月的气温数据,另一个记录了对应城市每月的降水量数据。请用Python结合Pandas和Matplotlib绘制出一个双Y轴图表,展示气温和降水量随月份的变化趋势,并且添加图例和清晰的坐标轴标注。
34.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
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文件包含citymonthtemperature列,precipitation.csv文件包含citymonthprecipitation列。以上代码实现了:

  1. 使用pandas读取两个CSV文件。
  2. 根据城市和月份合并两个数据框。
  3. 使用matplotlib创建双Y轴图表,分别绘制气温和降水量随月份的变化曲线,并添加坐标轴标注和图例。