I have been trying to plot mean of ‘Sales’ for 7 divisions (blue, green, grey, orange, purple, red, yellow) for each response month. Here is a code snippet:
subset_sales = (df_2.pivot_table(index=['Response Month (YYYY-MM)'], columns='Division', values='Sales') .reset_index() .set_index('Response Month (YYYY-MM)') ) subset_sales.plot(kind='line', rot=90) plt.tight_layout() plt.show()
How can I ensure that colour of plot line for each division matches the name of the division i.e. ‘blue’ colour plotline for blue division, ‘yellow’ colour plotline for yellow division?
Advertisement
Answer
You need to use style
to assign line color. The expectation is that you pass a dictionary of column and color pairs to style. As your column names are the color you want to assign to each line, you need to have each entry as 'Blue':'Blue'
and so on. So, you can update your plot as below…
subset_sales.plot(kind='line', rot=90, style={c: i for i, c in zip(subset_sales.columns, subset_sales.columns)})
and you will get the below plot.