0

I'm currently trying to change the linestyle and alpha values for a timeseries but I'm struggling to find a solution. There was a similar question where people solve this for numpy arrays but I am failing to take this in to work with a dataframe. For a dataframe 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)})

Now what I would like to do is to plot column 'vals' where the column 'filt' is equal to 0 and change the linestyle and alpha for the intervals where the index is smaller than 50 and larger than 150. Following the link mentioned above I tried:

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)

Which currently is returning a ValueError. How can I solve this? (preferably in a way I can later apply to different columns in the same dataframe)

Thanks

Chicrala
  • 994
  • 12
  • 23

2 Answers2

1

You could use pandas built-in plotting functions:

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)

enter image description here

Stef
  • 28,728
  • 2
  • 24
  • 52
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()

enter image description here

Thomas
  • 82
  • 10