python plotly area chart with Y-axis in percent - python

i try to plot the y-axis in percent. i there a way like in excel, excel scale automacily from 0 -100% ? or it is necessary first to calculate (group by year and continent) in the dataframe?
import plotly.express as px
df = px.data.gapminder()
fig = px.area(df, x="year", y="pop", color="continent",
line_group="country")
fig.show()
thanks for helP!

try this:
import plotly.express as px
df = px.data.gapminder()
dfw = df.groupby(['continent','year'])['pop'].sum().to_frame()
dfw.reset_index(inplace=True)
fig = px.area(dfw, x="year", y="pop", color="continent", groupnorm='fraction')
fig.update_layout(yaxis_tickformat='%')
fig.show()

Related

Plotly: How to display the total sum of the values at top of a stacked bar chart along with the individual bar values?

I am trying to add the total at the top of the each stacked bar along with the individual bar values in Plotly Express in Python.
import plotly.express as px
df = px.data.medals_long()
fig = px.bar(df, x="medal", y="count", color="nation", text_auto=True)
fig.show()
This gives the below result
However I want the chart as below:
Although it can be annotated as a string, the easiest way is to add a graph in the text mode of a scatter plot.
import plotly.express as px
import plotly.graph_objects as go
df = px.data.medals_long()
dfs = df.groupby('medal').sum()
fig = px.bar(df, x="medal", y="count", color="nation", text_auto=True)
fig.add_trace(go.Scatter(
x=dfs.index,
y=dfs['count'],
text=dfs['count'],
mode='text',
textposition='top center',
textfont=dict(
size=18,
),
showlegend=False
))
fig.update_yaxes(range=[0,50])
fig.show()

How to specify the x coordinate on a grouped bar chart on plotly?

I made a bar chart with python plotly, and I want to put a marker on a particular bar, example non-smoking females.
Does anyone know how to specify this?
I took an example from the plotly documentation, if I try to put the marker it just takes the center of the main category.
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="sex", y="total_bill",
color='smoker', barmode='group',
height=400)
#trying to set the marker
fig.add_trace(
go.Scatter(x=["Female"],
y=[1100]
))
fig.show()
inspired by this: https://community.plotly.com/t/grouped-bar-charts-with-corresponding-line-chart/19562/4
use xaxis2, work out position, have hardcoded it, but 0.15 has relationship to number of traces in bargoup and x value
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
df = px.data.tips()
fig = px.histogram(
df, x="sex", y="total_bill", color="smoker", barmode="group", height=400
)
# trying to set the marker
fig.add_trace(
go.Scatter(
x=[0.15],
y=[1100],
customdata=[["No", "Female"]],
xaxis="x2",
hovertemplate="smoker=%{customdata[0]}<br>sex=%{customdata[1]}<br>sum of total_bill=%{y}<extra></extra>",
)
)
fig.update_layout(xaxis2={"overlaying": "x", "range": [0, 1], "showticklabels": False})
fig

plotly separation with many bin

Given grouped bins , is there a way of having a larger gap between the bins? in
I.e, in the desired output, every bar/bar group has a predefined space around it.
# Change the default stacking
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill",
color='smoker', barmode='group',
height=400)
fig.show()
After building a figure you can adjust the gap between the bars like this:
fig.layout.bargap = 0.8
I've used 0.8 just to clearly illustrate the effects, but that number can be set to any int or float in the interval [0, 1]
Complete code:
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill",
color='smoker', barmode='group',
height=400)
f = fig.full_figure_for_development(warn=False)
fig.layout.bargap = 0.8
fig.show()

Changing the within-group order of a grouped bar plot in plotly

I'd like to change the order of my within-group variable in a plotly bar plot in Python.
For example, how can I switch the order of lunch and dinner here?
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x='sex', y='total_bill', color='time', barmode='group')
fig.show()
categoryorder can only change the order of groups, i.e. Male and Female.
Sort the df in descending order basis the column time.
import plotly.express as px
df = px.data.tips()
df.sort_values(['time'],ascending=[False],inplace=True)
fig = px.bar(df, x='sex', y='total_bill', color='time', barmode='group')
fig.show()
OUTPUT:

How to show timestamp x-axis in Python Plotly

I want to plot this data to evaluate data availability. I used the following plotting code in Plotly.
import datetime
import plotly.express as px
fig = px.bar(df, x=df.index, y="variable", color='value', orientation="h",
hover_data=[df.index],
height=350,
color_continuous_scale=['firebrick', '#2ca02c'],
title='',
template='plotly_white',
)
The result is just like what I want below.
But, the x-index show numbers. I want a timestamp (month+year) on the x-axis, instead.
Edit
Adding the fllowing
fig.update_layout(yaxis=dict(title=''),
xaxis=dict(
title='Timestamp',
tickformat = '%Y-%b',
)
)
Gives
which seems that the x-axis is not read from the data index.
If you want to use bars it seems to me that you need to find a nice workaround. Have you considered to use Heatmap?
import pandas as pd
import plotly.graph_objs as go
df = pd.read_csv("availability3.txt",
parse_dates=["Timestamp"])\
.drop("Unnamed: 0", axis=1)
# you want to have variable as columns
df = pd.pivot_table(df,
index="Timestamp",
columns="variable",
values="value")
fig = go.Figure()
fig.add_trace(
go.Heatmap(
z=df.values.T,
x=df.index,
y=df.columns,
colorscale='RdYlGn',
xgap=1,
ygap=2)
)
fig.show()

Categories

Resources