Reputation: 441
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
Upvotes: 3
Views: 1829
Reputation: 13447
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)
Upvotes: 4