How can i use Plotly express to make a 1D histogram without making new x values for each row of the same value?

Viewed 135

This is how my plot actually is: current output

This is the Data Frame: DataFrame

This is my current code:


import pandas as pd
import plotly.express as px

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)

df = pd.read_csv('sales.csv')

df.columns = df.columns.str.replace(' ', '')

fig= px.bar(df, x='number', y='number', color='profit')
fig.show()

As you can see, the sales numbers are many times the same, so i want to plot a histogram being each x value the total profit of all sales with the same key number, so i can compare the profit of each sales key number.

How can i do that using Pandas and plotly express?

ps: I'm a real noobie with all this

1 Answers
  • there is something up with your data frame. Have simulated it and used your code to generate figure. It generates a very different figure (see first image below)
    • I suspect there is something up with your dataframe, number columns are not numbers but strings. check df.dtypes
    • this is implied by xaxis being unordered and the fact color does not generate a color bar, but uses sequential colors
  • have demonstrated approach to getting total profit by sales number. Aggregate first with pandas then plot number as xaxis and profit as yaxis
import numpy as np
import pandas as pd
import plotly.express as px

# simulate data frame
df = pd.DataFrame({"number": np.repeat(np.arange(3334, 3389), 6)}).pipe(
    lambda d: d.assign(profit=np.random.uniform(-10, 200, len(d)))
)

# question approach
fig = px.bar(df, x="number", y="number", color="profit")
fig.show()

# requested approach
fig = px.bar(
    df.groupby("number", as_index=False).agg({"profit": "sum"}), x="number", y="profit"
).update_layout(xaxis={"type": "category"})

fig.show()

enter image description here

Related