Short answer:
This has nothing to do with opacity. For some more details take a look below at the complete answer. To obtain consisteny between a figures with many and few observations, you'll have to set the width of the bar line to zero, and set bargap to zero like in the next code snippet. Using a color like rgba(0,0,250,0)
you can also select any opacity you'd like through the last digit.
fig.update_traces(marker_color = 'rgba(0,0,250, 0.5)',
marker_line_width = 0,
selector=dict(type="bar"))
fig.update_layout(bargap=0,
bargroupgap = 0,
)
Plot 1a - Few observations
Plot 1b - Many observations
The details:
This has nothing to do with opacity
. You're asking plotly to build a bar-plot, and apparently barplots according to plotly must have a space between the bars. So for a few observations you'll get this:
And for many observations, as you have demonstrated, you'll get this:
The color of the bars has not changed, but it seems like it since plolty squeezes in a bit of space for many more observations.
I initially thought this would be amendable through:
fig.update_layout(bargap=0,
bargroupgap = 0,
)
But no:
In order to increase consistency between smaller and larger selectoins, you'll have to select the same color for the bar fill as for the line color of the bar, like blue
.
fig.update_traces(marker_color='blue',
marker_line_color='blue',
selector=dict(type="bar"))
But there's still a little color difference between the bars if you zoom in:
And this becomes clearer for lighter colors:
But the best solution turned out to be setting marker_line_width = 0
like described at the beginning of the answer.
End result:
Complete code:
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
import datetime
from plotly.subplots import make_subplots
pd.set_option('display.max_rows', None)
# data sample
nperiods = 50
np.random.seed(123)
df = pd.DataFrame(np.random.randint(-10, 12, size=(nperiods, 2)),
columns=['price', 'divergence'])
datelist = pd.date_range(datetime.datetime(2017, 1, 1).strftime('%Y-%m-%d'),periods=nperiods).tolist()
df['date'] = datelist
df = df.set_index(['date'])
df.index = pd.to_datetime(df.index)
# df.iloc[0] =1000
# df = df.cumsum().reset_index()
df.reset_index(inplace=True)
df['price'] = df['price'].cumsum()
df['divergence'] = df['divergence'].cumsum()
filtered = df[(df['date'] > '2017-1-24') & (df['date'] <= '2018-1-24')]
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(
go.Bar(
x=filtered['date'],
y=filtered['divergence'],
#opacity=0.5
)
)
fig.add_trace(
go.Scatter(
x=filtered['date'],
y=filtered['price'],
mode="lines"
),
secondary_y=True
)
fig.update_traces(marker_color = 'rgba(0,0,250, 0.5)',
marker_line_width = 0,
selector=dict(type="bar"))
fig.update_layout(bargap=0,
bargroupgap = 0,
)
fig.show()