Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

1D multiple lines plot with pandas

I have a dataframe with x1 and x2 columns. I want to plot each row as an unidimensional line where x1 is the start and x2 is the end. Follows I have my solution which is not very cool. Besides it is slow when plotting 900 lines in the same plot.

Create some example data:

import numpy as np
import pandas as pd    
df_lines = pd.DataFrame({'x1': np.linspace(1,50,50)*2, 'x2': np.linspace(1,50,50)*2+1})

My solution:

import matplotlib.pyplot as plt
def plot(dataframe):
    plt.figure()
    for item in dataframe.iterrows():
        x1 = int(item[1]['x1'])
        x2 = int(item[1]['x2'])
        plt.hlines(0,x1,x2)

plot(df_lines)

It actually works but I think it could be improved. Thanks in advance.

like image 614
ivangtorre Avatar asked Aug 10 '26 18:08

ivangtorre


1 Answers

You can use DataFrame.apply with axis=1 for process by rows:

def plot(dataframe):
    plt.figure()
    dataframe.apply(lambda x: plt.hlines(0,x['x1'],x['x2']), axis=1)

plot(df_lines)
like image 72
jezrael Avatar answered Aug 12 '26 06:08

jezrael