0

I'm trying to plot 4 types of data on a single graph using plotly. they all share the x-axis but one of them has a different y-axis to it, I want to plot the first few categories which share the x and y axis with different colors by category and a legend to match. and to plot the other data which has a different y axis on the same x axis as the previous data

I put together a simplified example of what I'm trying to do the Dataframe is like in the picture below and the code is my unsuccessful attempt of plotting.

enter image description here

import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots

fig = make_subplots(specs=[[{"secondary_y": True}]])
df = pd.DataFrame({"A":[1,np.nan],"B":[np.nan,1],'frq':[10,20]})
fig.add_trace(go.Bar(x=df.index ,y=df['A']),secondary_y=False)
fig.add_trace(go.Bar(x=df.index ,y=df['B']),secondary_y=False)
fig.add_trace(go.Scatter(x=df.index ,y=df['frq']),secondary_y=True)
fig.show()
px.bar(df).show()

The out come is as follows

enter image description here

I get a mess with sparse x axis sloths

using plotly.express I can easily plot the bar plot and get a decent graph(Down below ) but then it's problematic to add another y-axis for the other type of data

enter image description here

The desired outcome is something like this

enter image description here

I tried to look using pd.melt() to combine the sparse data and then to color it but then the legend becomes a problem.

I have found the solution evidently i had some Nan values or 0 values in the plotted data frame using the script bellow worked

fig = make_subplots(specs=[[{"secondary_y": True}]])
for column in colmns_list:
    f=df[[column]]
    f=f[f>0].dropna()
    fig.add_trace(
        go.Bar(x=f.index, y=f[column], name=column,),
        secondary_y=False
    )
Tomer Gigi
  • 33
  • 4
  • can you clarify what the desired outcome is? is the problem in the first chart that the scatter isn't centered on the bars? – Derek O Mar 09 '23 at 19:39
  • First, you should post only one problem per question. When your first question is solved, add your second one. But here I think you have 3 problems. – Hamzah Mar 09 '23 at 19:44

1 Answers1

0

I have found the solution evidently i had some Nan values or 0 values in the plotted data frame using the script bellow worked

fig = make_subplots(specs=[[{"secondary_y": True}]])
for column in colmns_list:
    f=df[[column]]
    f=f[f>0].dropna()
    fig.add_trace(
        go.Bar(x=f.index, y=f[column], name=column,),
        secondary_y=False
    )
Tomer Gigi
  • 33
  • 4