I've got a simple plotly line graph:
import plotly.express as px
fig = px.line(data, x="x-axis", y="variable")
fig.show()
I want to add data labels displaying each y-axis value to each point, but I can't work out how to do it using the plotly api. Is it possible? Can anyone point out how?
have simulated dataframe for your figure
two steps
define text parameter so trace / figure is built appropriately by Plotly Express
updated texttemplate so that formatting of y-axis is used
import plotly.express as px
import pandas as pd
import numpy as np
data = pd.DataFrame(
{
"x-axis": np.arange(0, 12),
"variable": (np.cos(np.linspace(np.pi / 2, np.pi, 12)) + 1) / 25,
}
)
fig = px.line(data, x="x-axis", y="variable", text="variable")
fig.update_traces(texttemplate="%{y}")
fig.update_layout(yaxis_tickformat=".2%")
Related
Code for the first image:
import plotly.express as px
fig = px.bar(data, x='date', y='oi_diff_nifty15800CE',title='Oi chain of Nifty 15800CE')
fig.update_layout(width=650,height=500)
fig.show()
Code for second image:
import plotly.express as px
fig = px.bar(data, x='date', y='oi_diff_nifty15800PE',title='Oi chain of Nifty 15800PE')
fig.update_layout(width=650,height=500)
fig.show()
you really need to state what you are trying to achieve beyond combining
have simulated data
two approaches here
use add_traces() to add traces from one figure to another figure
just change px.bar() parameters so it is generated as a single figure
import pandas as pd
import numpy as np
import plotly.express as px
# simulate data...
data = pd.DataFrame({"date": pd.date_range("21-jun-2021", periods=2),
"oi_diff_nifty15800CE": np.random.randint(5, 15, 2),
"oi_diff_nifty15800PE": np.random.randint(5, 15, 2),})
fig = px.bar(data, x="date", y="oi_diff_nifty15800CE", title="Oi chain of Nifty 15800CE")
# build from two different figures
fig.update_layout(width=650, height=300).add_traces(
px.bar(data, x="date", y="oi_diff_nifty15800PE", title="Oi chain of Nifty 15800PE").data).show()
# just change params...
px.bar(data, x="date", y=["oi_diff_nifty15800PE","oi_diff_nifty15800CE"], barmode="group").update_layout(width=650, height=300).show()
When I specify a range of y, the graph is not displayed correctly in that range.
I want to display the y-axis in the range of 10f~5u on the log scale, but it doesn't display properly. How can I solve this problem?
# imports
import pandas as pd
import plotly.graph_objs as go
import numpy as np
# data
np.random.seed(4)
x = np.linspace(0, 1, 50)
y = np.cumsum(np.random.randn(50))
# plotly line chart
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[10 ** -15, 5 * 10 ** -6])
fig.update_layout(
xaxis_type="linear",
yaxis_type="log",
)
fig.show()
In the documentation for log plots, it says that
Setting the range of a logarithmic axis with plotly.graph_objects is very different than setting the range of linear axes: the range is set using the exponent rather than the actual value:
So for your example, you can remove the 10 ** when setting the range, and your range can look like [-15, 1.000011]
The output with this change produces a graph that looks like this:
For reference, the complete code looks like:
# imports
import pandas as pd
import plotly.graph_objs as go
import numpy as np
# data
np.random.seed(4)
x = np.linspace(0, 1, 50)
y = np.cumsum(np.random.randn(50))
# plotly line chart
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines'), layout_yaxis_range=[-15, 1.000011])
fig.update_layout(
xaxis_type="linear",
yaxis_type="log",
)
fig.show()
I want to make a histogram with this style:
But using plotly in Python. I.e. I want to merge the bars and plot only the contour. I am using this code:
import plotly.graph_objects as go
import numpy as np
x = np.random.randn(500)
fig = go.Figure(data=[go.Histogram(x=x)])
fig.show()
I have been looking for examples on how to do this but could not find any.
Your best option is to handle the histogram with numpy like count, index = np.histogram(df['data'], bins=25) , and then use go.Scatter() and set the linetype to horizontal, vertical, horizontal with line=dict(width = 1, shape='hvh'). Take a look at the very last section why go.Histogram() will not be your best option. With a few other specifications for the layout of go.Scatter(), the snippet below will produce the following plot:
Complete code
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import plotly.io as pio
import plotly.express as px
pio.templates.default = "plotly_white"
# random numbers to a df
np.random.seed(12)
df = pd.DataFrame({'data': np.random.randn(500)})
# produce histogram data wiht numpy
count, index = np.histogram(df['data'], bins=25)
# plotly, go.Scatter with line shape set to 'hvh'
fig = go.Figure()
fig.add_traces(go.Scatter(x=index, y = count,
line=dict(width = 1, shape='hvh')))
# y-axis cosmetics
fig.update_yaxes(
showgrid=False,
ticks="inside",
tickson="boundaries",
ticklen=10,
showline=True,
linewidth=1,
linecolor='black',
mirror=True,
zeroline=False)
# x-axis cosmetics
fig.update_xaxes(
showgrid=False,
ticks="inside",
tickson="boundaries",
ticklen=10,
showline=True,
linewidth=1,
linecolor='black',
mirror=True,
zeroline=False)
fig.show()
Why go.Scatter() and not go.Histogram()?
The closest you'll get to your desired plot using your approach with fig = go.Figure(data=[go.Histogram(x=x)]) is this:
And that's pretty close, but you specifically wanted to exclude the vertical lines for each "bar". And I have yet not found a way to exclude or hide them with the go.Histogram setup.
Code for go.Histogram()
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import plotly.io as pio
import plotly.express as px
pio.templates.default = "plotly_white"
import numpy as np
x = np.random.randn(500)
fig = go.Figure(data=[go.Histogram(x=x)])
fig.update_traces(marker=dict(color='rgba(0,0,0,0)', line=dict(width=1, color='blue')))
fig.show()
for a variation plotly.go.Histogram(): Show only horizontal lines of distribution. Plot just the lines
using pandas instead of numpy to build data for histogram then plotting as a line scatter
import plotly.graph_objects as go
import numpy as np
import pandas as pd
x = np.random.randn(100)
# build data frame that is histogram
df = pd.cut(x, bins=10).value_counts().to_frame().assign(
l=lambda d: pd.IntervalIndex(d.index).left,
r=lambda d: pd.IntervalIndex(d.index).right,
).sort_values(["l","r"]).rename(columns={0:"y"}).astype(float)
# lines in plotly are delimited by none
def line_array(df, cols):
return np.pad(
df.loc[:, cols].values, [(0, 0), (0, 1)], constant_values=None
).reshape(1, (len(df) * 3))[0]
# plot just lines
go.Figure(go.Scatter(x=line_array(df, ["l","r"]), y=line_array(df, ["y","y"]), marker={"color":"black"}))
My goal is to create an animation with my 3D data in plotly.
I have 3 variables x,y,z for simplicity and I plot the 4th value depending on these x,y,z.
I create a 3D scatter plot where the 4th dim sort to speak is the color like this:
from numpy import genfromtxt
import numpy as np
import plotly.io as pio
import plotly.express as px
pio.renderers.default = 'notebook'
import plotly.graph_objects as go
import math
import pandas as pd
data = pd.read_csv("paramtp_1e-05_big.txt")
data.head()
data = data.iloc[::10, :]
color_data = data['gopt'].astype(float).round(decimals=2)
color_data[color_data>= 10] = 10
color_data_nopt = data['nopt'].astype(float).round(decimals=3)
color_data_mc = data['mc'].astype(float).round(decimals=3)
color_data_P= data['P']
color_data_P[color_data_P >= 1] = 1
data= data.replace(np.nan, '', regex=True)
data.tail()
fig = px.scatter_3d(data, x='NpN0', y='s', z='mu',log_x=True, log_z=True,
opacity = 0.5,
color=color_data,color_continuous_scale=px.colors.sequential.Viridis)
fig.add_trace(
go.Scatter(
mode='markers',
marker=dict(
size=1,
opacity=0.5,
),
)
)
fig.show()
Similarly to this wonderful animation: https://plotly.com/python/visualizing-mri-volume-slices/
I would like to slice up my data to isosurfaces with respect to any x,y,z coordinates.
As in the example they use images, I could not wrap my head around to create the same with my raw data.
Thank you in advance.
I have a plotly-dash dashboard and I can't seem to rescale my secondary y-axis. Is there a way of doing this?
I've tried messing with the domain parameter and the range parameter in the go.Layout.
I need the volume bar chart to be scaled down and occupy maybe 10% of the height of the plot so it doesn't overlap with my candlesticks.
Thank you very much.
Any help is appreciated.
import pandas as pd
import pandas_datareader.data as web
import plotly.offline as pyo
import plotly.graph_objs as go
stock_ticker='AAPL'
start_date='2019-04-01'
end_date='2019-05-22'
data=[]
hist_stock_df = web.DataReader(stock_ticker,'iex',start_date, end_date)
data.append(go.Candlestick(x=hist_stock_df.index,
open=hist_stock_df['open'],
high=hist_stock_df['high'],
low=hist_stock_df['low'],
close=hist_stock_df['close'],
name='AAPL'))
data.append(go.Bar(x=hist_stock_df.index,
y=hist_stock_df['volume'].values,
yaxis='y2'))
#y0=1000000
layout=go.Layout(title= 'Candestick Chart of AAPL',
xaxis=dict(title='Date',rangeslider=dict(visible=False)),
yaxis=dict(title='Price'),
plot_bgcolor='#9b9b9b',
paper_bgcolor='#9b9b9b',
font=dict(color='#c4c4c4'),
yaxis2=dict(title='Volume',
overlaying='y',
side='right'))
#scaleanchor='y'))
#scaleratio=0.00000001,
#rangemode='tozero',
#constraintoward='bottom',
#domain=[0,0.1]))
fig = go.Figure(data=data, layout=layout)
pyo.iplot(fig)
I have tried messing with the commented parameters
UPDATE
With this combination of layout parameters I managed to rescale the bars, but now there are two x-axis, been trying to figure out how to bring the middle x-axis down.
layout=go.Layout(title= 'Candestick Chart of AAPL',
xaxis=dict(title='Date',rangeslider=dict(visible=False)),
yaxis=dict(title='Price'),
plot_bgcolor='#9b9b9b',
paper_bgcolor='#9b9b9b',
font=dict(color='#c4c4c4'),
yaxis2=dict(title='Volume',
overlaying='y',
side='right',
scaleanchor='y',
scaleratio=0.0000001))
Use secondary_y=True or secondary_y=False within fig.update_yaxes() to specify which axis to adjust.
Plot 1: Without manual adjustments
Plot 2: With manual adjustments
Code:
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import datetime
# data
np.random.seed(1234)
numdays=20
dates = pd.date_range('1/1/2020', periods=numdays)
A = (np.random.randint(low=-10, high=10, size=numdays).cumsum()+100).tolist()
B = (np.random.randint(low=0, high=100, size=numdays).tolist())
df = pd.DataFrame({'A': A,'B':B}, index=dates)
# plotly figure setup
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(go.Scatter(name='A', x=df.index, y=df['A'].values))
fig.add_trace(go.Bar(name='B', x=df.index, y=df['B'].values), secondary_y=True)
# plotly manual axis adjustments
fig.update_yaxes(range=[50,160], secondary_y=False)
fig.update_yaxes(range=[-10,200], secondary_y=True)
fig.show()