-1

I have a DataFrame like this:

  Type Week Value
0  A    1    11
1  A    2     1
2  A    3     7
3  B    1    13
4  B    2    20
5  B    3    30

I would like to make a plot likedf.plot.bar() so that it looks like this:

enter image description here

How can I do that?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Brise
  • 11
  • 3

3 Answers3

2

I used Seaborn to do that plot:

import pandas as pd
import seaborn as sns

data=[['A',1,11],['A',2,1],['A',3,7],['B',1,13],['B',2,20],['B',3,30]]
df=pd.DataFrame(data,columns=['Type','Week','Value'])

sns.barplot(x='Type', y='Value', data=df, hue='Week');

With Seaborn you can choose properly the X an Y to plot, and using the parameter hue to show the values in each week. Seaborn is based on matplotlib, so the functions you use in plt are applied in Seaborn too (like plt.legend(), plt.xlabel(), etc.).

0

To elaborate on the comment from @QuangHoang, there are 2 steps to the process.

First, pivot the data.

pivoted = df.pivot('Type', 'Week', 'Value') 
pivoted
# Week   1   2   3
# Type            
# A     11   1   7
# B     13  20  30

The reason for this is outlined in the documentation for DataFrame.plot.bar (emphasis is mine).

x : label or position, optional. Allows plotting of one column versus another. If not specified, the index of the DataFrame is used.

y : label or position, optional. Allows plotting of one column versus another. If not specified, all numerical columns are used.

If neither argument is specified, it uses the Type index for x and every numerical column, now one per week, to get the y values for many bars. That's exactly what you want.

pivoted.plot.bar()
mcskinner
  • 2,620
  • 1
  • 11
  • 21
0

Given that the pandas solution is the one provided by @Quang Hoang if you have tidy datasets as in your case you could use seaborn as suggested by @Leonardo Araújo or plotly (which returns a nice interactive plot) as in the following

import pandas as pd
import plotly.express as px

data = [['A',1,11],
        ['A',2,1],
        ['A',3,7],
        ['B',1,13],
        ['B',2,20],
        ['B',3,30]]
df = pd.DataFrame(data, columns=['Type','Week','Value'])

# you need this as you want week to be category and not continuous
df["Week"] = df["Week"].astype(str)
px.bar(df, x="Type", y="Value", color="Week", barmode="group")

enter image description here

rpanai
  • 12,515
  • 2
  • 42
  • 64