Adding a market to a line chart Plotly python - python

I'm trying to add a point to the last observation on a time series chart with plotly. It is not very different from the example here https://stackoverflow.com/a/72539011/3021252 for instance. Except it is the last observation. Unfortunately following such pattern modifies the axis range.
Here is an example of an original chart
import plotly.express as px
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
fig.show()
But after adding a marker
import plotly.graph_objects as go
fig.add_trace(
go.Scatter(
x=[df["year"].values[-1]],
y=[df["lifeExp"].values[-1]],
mode='markers'
)
)
It looks like that
Has anyone have an idea how not to introduce this gap on the right?

Related

How to add a secondary Y axis to a Plotly Express bar plot?

I would like to add a second Y axis to my bar plot bellow, that is the number of citizens in integer:
this graph was made using plotly:
import plotly.express as px
fig = px.bar(df, x="country",y="pourcent_visit",color="city",barmode='group')
# fig.add_hline(y=10)
fig.show()
To my knowledge, there's no direct way to do this. But you can easily build a Plotly Express figure, grab the traces (and data structures) from there and combine them in a figure that allows multiple axes using fig = make_subplots(specs=[[{"secondary_y": True}]]). With no provided data sample, I'll use the built-in dataset px.data.tips() that I'm guessing to a large part resembles the structure of your real world dataset judging by the way you've applied the arguments in px.bar(). Details in the comments, but please don't hesitate to let me know if something is unclear.
Plot:
Complete code:
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
# sample data
df = px.data.tips()
# figure setup with multiple axes
fig = make_subplots(specs=[[{"secondary_y": True}]])
# build plotly express plot
fig2 = px.bar(df, x="day", y="total_bill", color="smoker", barmode="group")
# add traces from plotly express figure to first figure
for t in fig2.select_traces():
fig.add_trace(t, secondary_y = False)
# handle data for secondary axis
df2 = df.groupby('day').agg('sum')#.reset_index()
df2 = df2.reindex(index = df['day'].unique()).reset_index()
#
fig.add_trace(go.Scatter(x = df2['day'], y = df2['size'], mode = 'lines'), secondary_y = True)
# fix layout
fig.update_layout(legend_title_text = 'smoker')
fig.show()

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 Insert numerical information at plotly chart legend

I'm trying to added some data at my chart legends but i don't know how. I did search at plotly docs at https://plotly.com/python/legend/ but none of those examples available bring this feature. In the figure below is showed what i want to do. As you can see there is a legend of my chart and i want insert the data corresponded to the name of legend, i.g: UCL - 100, ICL - 50 and so on.
Here is what i have:
Here is a real example of what i really aim to:
A piece of the code i'm using is below, I can't share the rest:
fig.add_trace(go.Scatter(
x=df_mean_control_chart['Samples'],
y=df_mean_control_chart['UCL'],
mode='lines',
name='UCL',
line=dict(color='black', width=2)))
Description of the variables:
df_mean_control_chart['Samples'] and df_mean_control_chart['UCL'] = it's a column of a data from a dataframe which only contains numerical data.
You can add numerical values to the legend by using f-string to add the numerical value you wish to add to the legend.
import plotly.express as px
import plotly.graph_objects as go
df = px.data.stocks()
goog_max = df['GOOG'].max()
goog_mean = df['GOOG'].mean()
goog_min = df['GOOG'].min()
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.index, y=df['GOOG'], name='GOOG'))
fig.add_trace(go.Scatter(mode='lines',
x=df.index,
y=[goog_mean]*len(df),
name=f'GOOG {round(goog_mean,2)}'))
fig.add_trace(go.Scatter(mode='lines',
x=df.index,
y=[goog_max]*len(df),
name=f'GOOG {round(goog_max,2)}'))
fig.add_trace(go.Scatter(mode='lines',
x=df.index,
y=[goog_min]*len(df),
name=f'GOOG {round(goog_min,2)}'))
fig.show()

Plotting bars with 5 min interval and adding a line

I am trying to plot closing price with positive and negative sentiment. I was able to plot it as the picture below; however, the colors are not showing properly for the bar chart. Any ideas how to change them?
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig2 = make_subplots(specs=[[{"secondary_y": True}]])
fig2.add_trace(go.Scatter(x=data.index,y=data['close'],name='Price'),secondary_y=False)
fig2.add_trace(go.Bar(x=data.index,y=data['pos'],name='Positive'),secondary_y=True)
fig2.add_trace(go.Bar(x=data.index,y=data['neg'],name='Negative'),secondary_y=True)
fig2.show()
have implied you dataframe structure from your code and used plotly finance sample data set as starting point
two things to look at wrt to layout
make Close trace the primary trace at front
review bargroup parameter and reduce bargap to zero
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv"
)
# make plotly dataset compatible with OP implied structure
data = df.set_index(pd.date_range("1-Jan-2022", freq="5Min", periods=len(df))).rename(
columns={"AAPL.Close": "close", "dn": "neg", "up": "pos"}
)
fig2 = make_subplots(specs=[[{"secondary_y": True}]])
fig2.add_trace(
go.Scatter(x=data.index, y=data["close"], name="Price"), secondary_y=False
)
fig2.add_trace(go.Bar(x=data.index, y=data["pos"], name="Positive"), secondary_y=True)
fig2.add_trace(go.Bar(x=data.index, y=data["neg"], name="Negative"), secondary_y=True)
# a few changes to make layout work better
# 1. put close at front
# 2. reduce "whitespace" in bars
fig2.update_layout(
yaxis={"overlaying": "y2"}, yaxis2={"overlaying": None}, barmode="overlay", bargap=0
)

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