【问题标题】:How to change a dataframe plot style along the x axis based on its values?如何根据其值沿 x 轴更改数据框绘图样式?
【发布时间】:2019-12-10 11:24:07
【问题描述】:

我目前正在尝试更改时间序列的线型和 alpha 值,但我正在努力寻找解决方案。有一个类似的question,人们在其中解决了 numpy 数组的问题,但我无法将其用于数据框。对于数据框 a

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

a = pd.DataFrame({'vals':np.arange(200),'filt':(np.random.rand(200) > 0.5).astype(int)})

现在我想做的是在“filt”列等于 0 的地方绘制“vals”列,并更改索引小于 50 和大于 150 的间隔的线型和 alpha。按照上面提到的链接我试过了:

fig, ax = plt.subplots()
# Plot the values with index below 50 with 'filt' = 0.
ax.plot(a[(a.index < 50) | (a.filt == 0)].index.ravel(),a[(a.index < 50) | (a.filt == value)]['vals'].ravel(), alpha=.5)

# Plot the values with index between 50 and 150 with 'filt' = 0.
ax.plot(a.loc[a.filt == 0].index[(a.index <= 150) & (a.index >= 50)].ravel(),a.loc[a.filt == value]['vals'][(a.index <= 150) & (a.index >= 50)].ravel())

# Plot the values with index above 150 with 'filt' = 0.
ax.plot(a[(a.index > 150) | (a.filt == 0)].index.ravel(),a[(a.index > 50) | (a.filt == value)]['vals'].ravel(), alpha=.5)

当前正在返回 ValueError。 我该如何解决这个问题? (最好以我以后可以应用于同一数据框中的不同列的方式)

谢谢

【问题讨论】:

  • 如果 df["column"] 是数据框列(系列),df["column"].values 是相应的 numpy 数组。知道这一点将允许应用任何 numpy 解决方案。
  • 这不就相当于使用ravel()吗?

标签: python pandas matplotlib


【解决方案1】:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

a = pd.DataFrame({'vals':np.arange(200),'filt':(np.random.rand(200) > 0.5).astype(int)})

fig, ax = plt.subplots()

ax.plot(a[(a.index < 50) & (a.filt == 0)].index.ravel(),a[(a.index < 50) & (a.filt == 0)]['vals'].ravel(), alpha=.5)
ax.plot(a[(a.filt == 0)& (a.index <= 150)& (a.index >= 50)]['vals'].ravel(), a[(a.filt == 0)& (a.index <= 150)& (a.index >= 50)]['vals'].index, ls="-.", alpha=.5)
ax.plot(a[(a.filt == 0)& (a.index >=150)]['vals'].ravel(), a[(a.filt == 0)& (a.index >= 150)]['vals'].index, ls="--", alpha=.5)

plt.show()

【讨论】:

    【解决方案2】:

    您可以使用 pandas 内置的绘图功能:

    ax = a[(a.index<50) & (a.filt==0)].vals.plot(alpha=.5)
    a[((a.index>=50) & (a.index<=150)) & (a.filt==0)].vals.plot(ax=ax)
    a[(a.index>150) & (a.filt==0)].vals.plot(alpha=.5, ax=ax)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-23
      • 2017-09-15
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多