Matplotlib绘图时如何仅展示高于特定阈值的数值及对应日期
解决方法
你可以直接使用Pandas的布尔索引筛选符合条件的完整行数据,不需要自行遍历列,该方式会自动保留所有关联列(包括对应的Week日期列)。
1. 数据筛选实现
筛选比利时percent列大于75的所有行的代码如下:
# 布尔索引筛选:仅保留percent大于75的行,自动保留Week等所有列 BE_filtered = BE[BE["percent"] > 75] # 如果需要同时筛选法国数据,同理操作 FR_filtered = FR[FR["percent"] > 75] # 如需查看筛选后的日期和对应percent值,执行以下代码即可 print(BE_filtered[["Week", "percent"]])
2. 修改绘图代码仅展示筛选后数据
把原来scatter方法里传入的原始DataFrame替换为筛选后的对象即可,完整修改后代码如下:
import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd # 导入数据 BE = pd.read_csv("BE-4YRS.csv") FR = pd.read_csv("FR-4YRS.csv") # 按阈值筛选数据 threshold = 75 BE_filtered = BE[BE["percent"] > threshold] FR_filtered = FR[FR["percent"] > threshold] # 绘图 fig, ax = plt.subplots() ax.scatter(BE_filtered["Week"], BE_filtered["percent"], alpha=0.7, c="r", s=BE_filtered["percent"]*2, label="Belgium") ax.scatter(FR_filtered["Week"], FR_filtered["percent"], alpha=0.7, c="b", s=FR_filtered["percent"]*2, label="France") ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.legend() plt.xticks(rotation=45) plt.grid(True) plt.show()
内容的提问来源于stack exchange,提问作者Adil
相关产品推荐
相关产品推荐

