【问题标题】:How to filter on index while creating a Matplotlib graph?创建 Matplotlib 图时如何过滤索引?
【发布时间】:2022-01-03 14:54:39
【问题描述】:

我正在尝试通过过滤索引列来创建 matplotlib 图,在我的数据框中是日期时间列。

以下是我创建未过滤图表的步骤。

import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame([1,2,3,4,5], index = [‘01/01/2021’,’01/02/2021’,’01/03/2021’,’01/04/2021’,’01/05/2021’], columns = [‘quantity’])

fig, axes = plt.subplots()
axes.scatter(data = df, x = df.index, y = ‘quantity’) 

这项工作符合预期。为了避免创建包含过滤数据的数据框,我试图在一行中创建过滤图,基本上是这样做的。

fig, axes = plt.subplot()
axes.scatter(data = df[df.index < ‘01/04/2021’], x = df.index, y = ‘quantity’)

这显然行不通,因为 x 和 y 的大小不同。

一种解决方法是在 df 中创建一个新列,它是索引的精确副本,但我想知道是否有一个更简单、更清晰的解决方案正在我的脑海中消失。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    你是绝对正确的。有两种方式:

    1. 过滤与数据相似的 x 值:
    fig, axes = plt.subplot()
    axes.scatter(data = df[df.index < '01/04/2021'], x = df[df.index < '01/04/2021'].index, y = 'quantity')
    
    1. 限制情节的一个轴:
    fig, axes = plt.subplot()
    axes.scatter(data = df, x = df.index, y = 'quantity')
    axes.xlim(df[df.index < '01/04/2021'].index)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-28
      • 1970-01-01
      • 2021-06-28
      • 2013-01-21
      • 2019-07-08
      • 2013-04-12
      • 1970-01-01
      相关资源
      最近更新 更多