Skip to content
Advertisement

How to plot a dataframe column of lists as horizontal lines

I have a Dataframe with the column 'all_maxs' that could have a list of different values.

JavaScript

Current Result

enter image description here

I need to plot column 'c', and the values of column 'all_maxs' that should be horizontal lines.

Expected Result

expected result

Advertisement

Answer

  1. Verify the 'all_maxs' values are list type.
  2. Extract values from the lists and plot them as horizontal lines.
    • df = df.dropna() if there are any NaN

Imports and DataFrame

  • Convert the 'all_maxs' column type from str to list if needed, using ast.liter_eval
JavaScript

Plot

  • Plot the dataframe directly with pandas.DataFrame.plot
    • xticks=df.index will make an xtick for every value in the index, but if there are many values crowding the x-axis, remove this parameter.
  • Use matplotlib.pyplot.hlines, which will accept a list of values, to plot the unique values from 'all_max' as horizontal lines.
    • Use pandas.DataFrame.explode to remove all the values from lists, and then drop duplicates with .drop_duplicates
    • y= will be the remaining values in the 'all_maxs' column
    • xmin= will be the remaining index values
    • xmax= will be the max value in the index plotted from df
JavaScript

enter image description here

Advertisement