0

I am trying to plot a chart. I can plot a line chart which can show 5 different color with 5 legend. I want to plot a bar chart which can show 5 different colors, but the bar chart I plot has only 1 color, may I know what's wrong with my code?

Here is my code:

import pandas as pd
import matplotlib as plt

df = pd.read_csv('df.csv')
df.set_index('date',inplace=True)

date        symbol  roe
31/12/2015  NEM -0.9866
31/12/2016  NEM -6.8385
31/12/2017  NEM -0.6164
31/12/2018  NEM 2.7824
31/12/2019  NEM 13.2141
31/12/2015  MLM 7.1164
31/12/2016  MLM 10.27
31/12/2017  MLM 15.2355
31/12/2018  MLM 9.5042
31/12/2019  MLM 11.4322
30/9/2015   APD 13.0861
30/9/2016   APD 15.5544
30/9/2017   APD 11.3416
30/9/2018   APD 13.3381
30/9/2019   APD 15.8882
31/12/2015  VMC 5.2291
31/12/2016  VMC 9.238
31/12/2017  VMC 11.9421
31/12/2018  VMC 9.9529
31/12/2019  VMC 11.0729
31/12/2015  FMC -11.1408
31/12/2016  FMC 6.558
31/12/2017  FMC -4.9167
31/12/2018  FMC 16.7456
31/12/2019  FMC 21.2189

I can plot a line chart:-

df.groupby('symbol')['roe'].plot(figsize=(10,8),legend='True')

enter image description here

I can plot a chart, but I want the chart have 5 different bar on each year with different color. May I know how to solve this?

df.groupby('symbol')['roe'].plot(kind='bar', legend='True', figsize = (5,5))

enter image description here

janicewww
  • 323
  • 1
  • 10

1 Answers1

0

Let's try groupby the year and plot:

for y,d in df.groupby(pd.to_datetime(df['date']).dt.year):
    ax = d.pivot('date','symbol','roe').plot.bar()
    ax.set_title(y)

You will have five different plots, each for a year that looks like this:

enter image description here

If you want to plot all of them into one plot, skip the groupby, just pivot and plot:

df.pivot('date','symbol','roe').plot.bar()

and get

enter image description here

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74
  • may i know is there has a function to remove the month and day on the datetime column? There has one issue with the symbol APD which the month and day is different with those 4 symbols. Thank you in advance x – janicewww Oct 21 '20 at 15:30
  • 1
    `df['date'].dt.year` if your `date` columns is of datetime type. – Quang Hoang Oct 21 '20 at 15:35