benr
benr

Reputation: 67

Plotly bar plot colored by week?

I am trying to make a what is a simple plot in excel but can't figure out how to do it in plotly. enter image description here I've tried:

px.bar(df, x=['A','B','D','E'], color='date')

but it gives a key error.

Upvotes: 1

Views: 87

Answers (2)

amance
amance

Reputation: 1770

Data is generally easier to work with when it's in long format the way @Kat showed, but if you wanted to keep your data frame as is, you could try this.

import numpy as np
import pandas as pd
import plotly.graph_objects as go


df = pd.DataFrame({'date':['8/5/2022', '8/12/2022'],
           'A':[0,20],
           'B':[0,20],
           'D':[80,40],
           'E':[20,0]})

print(df)
        date   A   B   D   E
0   8/5/2022   0   0  80  20
1  8/12/2022  20  20  40   0

fig = go.Figure()

for row in range(len(df)):
    fig.add_trace(go.Bar(x=df.columns[1:],
                 y=df.iloc[row][1:].tolist(),
                 name=df.iloc[row][0])
              )
fig.show()

Fig

Upvotes: 0

Kat
Kat

Reputation: 18714

There are many different ways that you can make this happen. I'm not sure how you brought the data into Python.

If you used a dictionary or a Pandas data frame, either of the two methods I'll show will work. The first uses Plotly Express, since that's what it appears you tried to use. The second method uses Plotly as a Pandas backend.

The Plotly Express Method

import plotly.express as px
import pandas as pd

d = ["8-5-2022", "8-12-2022"]
df1 = pd.DataFrame({"dt": d, "A": [0, 20], "B": [0, 20], "D": [80, 40], "E": [20, 0]})
df2 = df1.melt(id_vars = 'dt', value_vars = ['A', 'B', 'D', 'E'])
print(df2)
"""
          dt variable  value
0   8-5-2022        A      0
1  8-12-2022        A     20
2   8-5-2022        B      0
3  8-12-2022        B     20
4   8-5-2022        D     80
5  8-12-2022        D     40
6   8-5-2022        E     20
7  8-12-2022        E      0
"""
fig = px.bar(df2, x = 'variable', y = 'value', color = 'dt')
fig.show()

enter image description here

Using Plotly as a Pandas Backend

import pandas as pd
pd.options.plotting.backend = "plotly"

d = ["8-5-2022", "8-12-2022"]
df1 = pd.DataFrame({"dt": d, "A": [0, 20], "B": [0, 20], "D": [80, 40], "E": [20, 0]})

df2 = df1.melt(id_vars = 'dt', value_vars = ['A', 'B', 'D', 'E'])
print(df2)
"""
          dt variable  value
0   8-5-2022        A      0
1  8-12-2022        A     20
2   8-5-2022        B      0
3  8-12-2022        B     20
4   8-5-2022        D     80
5  8-12-2022        D     40
6   8-5-2022        E     20
7  8-12-2022        E      0
"""
fig = df2.plot.bar(x = "variable", y = "value", color = "dt")
fig.show()

enter image description here

Upvotes: 1

Related Questions