I am using plotly with python and I am trying to use use these kinds of tick in X and Y axis:
10-3, 10-4, 10-5, and so on..
Any suggestions or recoomended reading?
I am obtaining this:
I was also in a search for this feature, and found the solution in this other answer:
https://stackoverflow.com/a/56742105/418875
You should set exponentformat to the power option. This will print the ticks as shown below:
I believe the closes you'll get is logartihmic axes:
import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", hover_name="country", log_x=True)
fig.show()
This has been bugging me for a while, here's the best solution I've found:
TLDR, you can use HTML formatting to make sure the exponent is a superscript and use array mode to pass strings for the tick labels to plotly.
import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", hover_name="country", log_x=True)
tickvals = np.logspace(3,6, num=4)
print(tickvals)
def format_tick(n: float):
m, e = f"{n:.0e}".split("e")
e = int(e)
return f"{m} x 10<sup>{e}</sup>"
ticktext = [format_tick(t) for t in tickvals]
print(ticktext)
fig.update_layout(
xaxis = dict(
tickmode = 'array',
tickvals = tickvals,
ticktext = ticktext,
)
)
fig.show()
Related
I have code below as, but I cant seem to show legend even by trying a few things manually by showing legend parameter, is there anyway to show legend? Thanks!
subfig = make_subplots(specs=[[{"secondary_y": True}]])
# create two independent figures with px.line each containing data from multiple columns
fig = px.line(dfa, y="revenue", template=template_style,markers=True)
fig2 = px.line(dfa, y="pdt_chg", template=template_style,markers=True)
fig2.update_traces(yaxis="y2")
subfig.add_traces(fig.data + fig2.data)
subfig.layout.title="Sales"
subfig.layout.xaxis.title="Year"
subfig.layout.yaxis.title="$"
subfig.layout.yaxis2.title="%"
subfig.update_layout(
xaxis = dict(
tickmode = 'linear',
tick0 = 0,
dtick = 0),title_x= 0.47,template=template_style)
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))
subfig.show()
When px.line is prompted to produce a figure with a single line, the default behavior is to drop the legend. This is presumably intended to reduce redundant information since it's easy to include the data description in the main title and/or the axis title. In order to override this, just include:
fig.for_each_trace(lambda t: t.update(name = <a name>))
fig.update_traces(showlegend = True)
In your case, you'll have to do so for both your initial figures before they are joined in subfig. Here's and exampe with the gapminder dataset:
Plot:
Complete code:
import plotly.express as px
from plotly.subplots import make_subplots
subfig = make_subplots(specs=[[{"secondary_y": True}]])
df1 = px.data.gapminder().query("country=='Canada'")
fig1 = px.line(df1, x="year", y="lifeExp", title='Life expectancy in Canada')
fig1.for_each_trace(lambda t: t.update(name = 'Canada'))
fig1.update_traces(showlegend = True)
df2 = px.data.gapminder().query("country=='Germany'")
fig2 = px.line(df2, x="year", y="lifeExp", title='Life expectancy in Germany')
fig2.for_each_trace(lambda t: t.update(name = 'Germany'))
fig2.update_traces(showlegend = True)
subfig.add_traces(fig1.data + fig2.data)
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))
subfig.show()
In a scatter plot created using px.scatter, how do I mark one data point with a red star?
fig = px.scatter(df, x="sepal_width", y="sepal_length")
# Now set a single data point to color="red", symbol="star".
This isn't really highlighting an already existing data point within a trace you've already produced, but rather adding another one with a different visual appearance. But it does exactly what you're looking for:
fig.add_trace(go.Scatter(x=[3.5], y=[6.5], mode = 'markers',
marker_symbol = 'star',
marker_size = 15))
Plot:
Complete code:
import plotly.express as px
import pandas as pd
import plotly.graph_objects as go
df = px.data.iris() # iris is a pandas DataFrame
fig = px.scatter(df, x="sepal_width", y="sepal_length")
fig.add_trace(go.Scatter(x=[3.5], y=[6.5], mode = 'markers',
marker_symbol = 'star',
marker_size = 15))
fig.show()
This directly modifies the Scatter trace's Marker itself:
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length")
trace = next(fig.select_traces())
# Modify kth point.
n = len(trace.x)
k = 136
color = [trace.marker.color] * n
color[k] = "red"
size = [8] * n
size[k] = 15
symbol = [trace.marker.symbol] * n
symbol[k] = "star"
# Update trace.
trace.marker.color = color
trace.marker.size = size
trace.marker.symbol = symbol
# Alternatively, call:
# fig.update_traces(marker=dict(color=color, size=size, symbol=symbol))
fig.show()
I would like to modify a facetted plotly.express figure so that each trace has its own secondary y-axis. I don't want to re-create the figure from scratch using the standard Plotly-python api if possible. See exmaple below.
import plotly.express as px
input_df = px.data.tips()
fig = px.scatter(input_df,
x = 'total_bill',
y = 'tip',
color = 'day',
facet_row = 'smoker',
facet_col = 'sex',
)
fig.layout.width = 800
fig.show()
I would like to convert the above so each trace (or color) has its own secondary y-axis. So in this case, I would like 3 additional y-axes for each facet. This is my attempt but it doesn't work. There must be a better way. I would appreciate any ideas.
import plotly.graph_objects as go
yaxes = []
for trace in fig.data:
yaxisLabel = trace['yaxis']
if trace['yaxis'] in yaxes:
if yaxisLabel == 'y':
axisnumber = 0
else:
axisnumber = int(trace['yaxis'][1:])
newAxis_num = axisnumber + 100 * yaxes.count(yaxisLabel)
exec(f"fig.layout.update(yaxis{newAxis_num} = go.layout.YAxis(overlaying='y', side='right'))")
trace.update({'yaxis': f'y{newAxis_num}'})
yaxes.append(yaxisLabel)
I made a line graph with the code below and I'm trying to add a horizontal line at y=1. I tried following the instructions on the plotly site but it is still not showing. Does anyone know why?
date = can_tot_df.date
growth_factor = can_tot_df.growth_factor
trace0 = go.Scatter(
x=date,
y=growth_factor,
mode = 'lines',
name = 'growth_factor'
)
fig = go.Figure()
fig.add_shape(
type='line',
x0=date.min(),
y0=1,
x1=date.max(),
y1=1,
line=dict(
color='Red',
)
)
data = [trace0]
iplot(data)
Short answer, and a general solution:
fig.add_shape(type='line',
x0=0,
y0=40,
x1=8,
y1=40,
line=dict(color='Red',),
xref='x',
yref='y'
)
Details and specifics about OP's question
It's hard to tell exactly what's wrong without a sample of your data.
What I can tell for sure is that you're missing the arguments xref and yref to specify that the line is drawn as units of your y and x axis. Judging by your sample code, this is what you'd like to do since you're specifying your x-values in terms of dates.
Also, you don't need to worry about iplot for newer versions of plotly. You can display your chart just as easily by just running fig.show(). The figure and code sample below will show you how to use fig.show() and how to define your lines in terms of axis units.
Plot:
Code:
import plotly.graph_objects as go
import numpy as np
x = np.arange(10)
fig = go.Figure(data=go.Scatter(x=x, y=x**2))
fig.add_shape(type='line',
x0=0,
y0=40,
x1=8,
y1=40,
line=dict(color='Red',),
xref='x',
yref='y'
)
fig.show()
An alternative to xref='x' is xref='paper'. Now you can specify x0 as a float between 0 and 1 spanning from the start and end of the plot.
You could also use fig.add_hline(y=1) --> see https://plotly.com/python/horizontal-vertical-shapes/
import plotly.graph_objects as go
import numpy as np
x = np.arange(10)
fig = go.Figure(data=go.Scatter(x=x, y=x**2))
fig.add_hline(y=40, line_width=3, line_dash="dash", line_color="green")
fig.show()
If you use subplots, then this is the easiest way I found to add an other line to a subplot. this example draws a horizontal line at y=80 for all x values
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=1,
shared_xaxes=True,
vertical_spacing=0.02)
[some graph]
fig.add_trace(go.Scatter(
name='Y=80',
x = [df['date'].min(), df['date'].max()],
y = [80, 80],
mode = "lines",
marker = dict(color = 'rgba(80, 26, 80, 0.8)')
),row=1, col=1)
i found the solution on github :
df = df
fig = px.scatter(df, x="date", y="growth_factor", mode = 'lines',
hover_name=df['growth_factor'] )
fig.update_layout(shapes=[
dict(
type= 'line',
yref= 'y', y0= 1, y1= 1, # adding a horizontal line at Y = 1
xref= 'paper', x0= 0, x1= 1
)
])
fig.show()
You’re adding the line to your fig object, but fig is not getting passed into the iplot() function, only your data. So only the trace is getting plotted.
If you're using a late version of plotly, the new syntax allows you to create this plot simply using the fig object, like:
from plotly import graph_objects as go
fig = go.Figure()
# Contrived dataset for example.
x = [1, 2, 3, 4]
y = [i**2 for i in x]
fig.add_trace(go.Scatter(
x=x,
y=y,
mode = 'lines',
name = 'growth_factor'))
fig.add_shape(type='line',
x0=min(x),
y0=5,
x1=max(x),
y1=5,
line=dict(color='Red'))
fig.update_shapes(dict(xref='x', yref='y'))
fig.show()
Here are the plotly docs for convenience.
I am playing with examples from plotly.express piechart help page and trying to add an extra element iso_num to the hover_data property (iso_num is an int64 column in the gapminder dataframe)
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = px.pie(df, values='pop', names='country',
title='Population of American continent',
hover_data=['lifeExp','iso_num'], labels={'lifeExp':'life expectancy','iso_num':'iso num'
})
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
Hovering over the slice of the pie chart then gives this:
where iso num value is %{customdata[1]} instead of the numeric value from the column.
What am I missing?
Thanks!
I found a way to do it with Plotly Express Pie chart as well. You can use update_traces to define hover_template. It seems there is an issue with splitting on multiple values for hover_data/custom_data and all values are present at 0 index only i.e. both values are at customdata[0].
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = px.pie(df, values='pop', names='country',
title='Population of American continent',
custom_data=['lifeExp','iso_num'], labels={'lifeExp':'life expectancy','iso_num':'iso num'
})
fig.update_traces(textposition='inside', textinfo='percent+label',\
hovertemplate = "Country:%{label}: <br>Population: %{value} </br>(life expentancy, iso num) : %{customdata}"
)
fig.show()
On hover:
This seems to be a relic from back when it was stated that
Oh pie hover is a big mess
Which since seems to be have been resolved. But perhaps not for px.pie()?
I've tried numerous approaches, but I'm only able to get the customdata + hovertemplate approach to work for go.Pie and not for px.Pie. Here's a demonstration on how assigning values to customdata will make any variable otherwise not assigned to go.Pie() available for a custom hovertamplate:
Plot:
Code:
import plotly.graph_objects as go
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'")
fig = go.Figure(go.Pie(
name = "",
values = df['pop'],
labels = df['country'],
customdata=df['iso_num'],
hovertemplate = "Country:%{label}: <br>Population: %{value} </br> iso num:%{customdata}"
))
fig.show()