Degtiarev Aleksei
Degtiarev Aleksei

Reputation: 415

Add vertical line after each changing of value in column

I have such kind of data:

AccX                    RecordType
0.204742431640625       0
0.204742431640625       0
0.114715576171875       0
0.114715576171875       0
                ...             
0.033111572265625       1
0.033111572265625       1
0.0328826904296875      1
                ...
0.0328826904296875      2
0.0328826904296875      2
0.154434204101562       2

And code for constructing plot:

import matplotlib as mpl
mpl.use('MacOSX')

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

data = pd.read_csv('myData.csv')

figsize = (15, 7)
fig,ax = plt.subplots(figsize=figsize)

ax.plot(data['AccX'])

plt.legend()
plt.show()

How to add the line after each changing of the value of record type? Is it possible to add titles in the place between lines?

I mean to construct something like this: Example

Upvotes: 4

Views: 1466

Answers (1)

ALollz
ALollz

Reputation: 59579

You can use .diff() to find when a period changes and then plot a vertical line with plt.axvline()

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

data
AccX                    RecordType
0.204742431640625       0
0.204742431640625       0
0.114715576171875       0
0.114715576171875       0    
0.033111572265625       1
0.033111572265625       1
0.0328826904296875      1
0.0328826904296875      2
0.0328826904296875      2
0.154434204101562       2

# Determine when the RecordType Changes
periods = data[data.RecordType.diff()!=0].index.values

figsize = (12, 5)
fig,ax = plt.subplots(figsize=figsize)

ax.plot(data['AccX'])

# Plot the red vertical lines
for item in periods[1::]:
    plt.axvline(item, ymin=0, ymax=1,color='red')

# Plot the Record Text.
for i in range(len(periods)-1):
    plt.text(y=0.8*data['AccX'].max(), x=(periods[i]+periods[i+1]-1)/2,
        s='Record '+ str(i), color='red', fontsize=18)

plt.text(y=0.8*data['AccX'].max(), x=(periods[-1]+len(data)-1)/2,
    s='Record '+ str(len(periods)-1), color='red', fontsize=18)

plt.legend()
plt.show()

Plot

Upvotes: 3

Related Questions