3

I'm trying to create a bar chart in plotly and I want to have the x and y axis blank and to show the data on the bar itself instead (I know it's contained on the hover but this is intended to be used for presentations). I've created some dummy data below.

import random
import pandas as pd
import plotly.express as px

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
years = [2018,2019,2020]
sales = random.sample(range(10000),18)

df = pd.DataFrame(columns = ["Year", "Month", "Sales"])

df["Year"]= years*6
df.sort_values("Year", inplace = True)
df["Month"] = months*3
df["Sales"] = sales

For each bar I want to see the month and the sales value so something like "Jan - 543", "Feb - 1200" etc. I'm able to add the values from a single column to the bar chart, as per below for Sales

barchart = px.bar(
    data_frame = df.groupby(["Month"]).Sales.sum().reset_index(),
       x = "Sales",
       y = "Month",
    title = "Sales by Month 2018-2020",
        orientation = "h",
       barmode = "group",
      text = "Sales"
       )
barchart.update_xaxes(visible = False)
barchart.update_yaxes(visible = False)
pio.show(barchart)

Or as per below for Months but I can't combine the two

barchart = px.bar(
    data_frame = df.groupby(["Month"]).Sales.sum().reset_index(),
       x = "Sales",
       y = "Month",
    title = "Sales by Month 2018-2020",
        orientation = "h",
       barmode = "group",
      text = "Month"
       )
barchart.update_xaxes(visible = False)
barchart.update_yaxes(visible = False)
pio.show(barchart)

Any help would be greatly appreciated

1
  • You could skip pio.show(barchart) Commented Aug 25, 2020 at 2:21

1 Answer 1

4

It looks to me that is more a pandas problem than a plotly one. You could create a column with the given text output and pass it to plotly.express

import pandas as pd
import plotly.express as px

grp = df.groupby(["Month"])["Sales"].sum().reset_index()
grp["Text"] = grp["Month"] + " - "+ grp["Sales"].astype(str)
print(grp)
  Month  Sales         Text
0   Apr  15949  Apr - 15949
1   Feb  12266  Feb - 12266
2   Jan   9734   Jan - 9734
3   Jun  13771  Jun - 13771
4   Mar  24007  Mar - 24007
5   May  12720  May - 12720

and just plot grp

barchart = px.bar(
    data_frame = grp,
    x="Sales",
    y="Month",
    title="Sales by Month 2018-2020",
    orientation ="h",
    barmode="group",
    text="Text")
barchart.update_xaxes(visible = False)
barchart.update_yaxes(visible = False)
barchart.update_layout(title_x=0.5)

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.