Plotting multiple lines, in different colors, with pandas dataframe
Another simple way is to use the pandas.DataFrame.pivot
function to format the data.
Use pandas.DataFrame.plot
to plot. Providing the colors in the 'color'
column exist in matplotlib: List of named colors, they can be passed to the color
parameter.
# sample datadf = pd.DataFrame([['red', 0, 0], ['red', 1, 1], ['red', 2, 2], ['red', 3, 3], ['red', 4, 4], ['red', 5, 5], ['red', 6, 6], ['red', 7, 7], ['red', 8, 8], ['red', 9, 9], ['blue', 0, 0], ['blue', 1, 1], ['blue', 2, 4], ['blue', 3, 9], ['blue', 4, 16], ['blue', 5, 25], ['blue', 6, 36], ['blue', 7, 49], ['blue', 8, 64], ['blue', 9, 81]], columns=['color', 'x', 'y'])# pivot the data into the correct shapedf = df.pivot(index='x', columns='color', values='y')# display(df)color blue redx 0 0 01 1 12 4 23 9 34 16 45 25 56 36 67 49 78 64 89 81 9# plot the pivoted dataframe; if the column names aren't colors, remove color=df.columnsdf.plot(color=df.columns, figsize=(5, 3))
You could use groupby
to split the DataFrame into subgroups according to the color:
for key, grp in df.groupby(['color']):
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltdf = pd.read_table('data', sep='\s+')fig, ax = plt.subplots()for key, grp in df.groupby(['color']): ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)plt.legend(loc='best')plt.show()
yields