Plotly Express: Update the colorbar title - python

I'm using plotly Express density_heatmap and i'm trying to update manually the name of the legend (here the color continuous scale). I tried with labels, update_layout but it looks like i can't remove the 'sum of' or 'count' etc from the legend.
Here i modified example from plotly:
import plotly.express as px
dft = px.data.iris()
figt = px.density_heatmap(dft, x="sepal_width", y="sepal_length", z='sepal_length',
labels=dict(z='sepal_length'))
figt.show()
Is there a way to remove this sum of?
Thanks in andvance

You can use:
figt.update_layout(coloraxis_colorbar_title_text = 'your title')
Plot:
Complete code:
import plotly.express as px
dft = px.data.iris()
figt = px.density_heatmap(dft, x="sepal_width", y="sepal_length", z='sepal_length',
labels=dict(z='sepal_length'))
figt.update_layout(coloraxis_colorbar_title_text = 'your title')
figt.show()

Related

Plotly Express Overlay Two Line Graphs

I know that it is easy to overlay plots using Plotly Go.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]),
go.Scatter(x=[1,2,3], y=[2,1,2]),
go.Scatter(x=[1,2,3], y=[1,1,2])])
fig.show()
However, I would like to accomplish same task using Poltly Express. Is there a way to accomplish such a task in Plotly Express?
You can do it with add_traces
import pandas as pd
import numpy as np
import plotly.express as px
data = {'x':[1,2,3], 'y':range(3)}
df1 = pd.DataFrame(data)
data = {'x':[4,5,6], 'y':range(4,7)}
df2 = pd.DataFrame(data)
fig1 = px.line(df1, x='x', y='y', color_discrete_sequence=['red'])
fig2 = px.line(df2, x='x', y='y', labels='green', color_discrete_sequence=['green'])
fig1.add_traces(
list(fig2.select_traces())
)
name = ['red','green']
for i in range(len(fig1.data)):
fig1.data[i]['name'] = name[i]
fig1.data[i]['showlegend'] = True
fig1.show()
However, I prefer to use go plots, which are easier.

Plotly python add annotation to display all column values at every point

I am trying to plot all column values at each point when we hover over a data point in plotly
My code is as follows
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
import pandas as pd
# data
pio.templates.default = "plotly_white"
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df_s = df[['Date','AAPL.Open','AAPL.High','AAPL.Low','dn','mavg'
]]
df_s = df_s.set_index('Date')
df_s.tail()
cols = df_s.columns
ncols = len(cols)
# subplot setup
fig = make_subplots(rows=ncols, cols=1, shared_xaxes=True)
for i, col in enumerate(cols, start=1):
fig.add_trace(go.Scatter(x=df_s[col].index, y=df_s[col].values, name=df_s[col].name), row=i, col=1)
fig.update_layout(
autosize=False,
width=1200,
height=800,)
fig.show()
Currently when I hover over the datapoint it shows value for that column alone. I am interested in seeing
Values for 'Date','AAPL.Open','AAPL.High','AAPL.Low','dn','mavg' these columns at a particular row whenever I hover over anyplot
I tried add_annotations with no luck. Is there a way of doing it? Thank you in advance
As #Marco_CH pointed out, this exact feature doesn't exist in Plotly. However, you can try using a unified hovermode on the x-axis so there is only one hoverbox, and remove the date from each hovertemplate since it's already shown at the top of the hoverbox.
import pandas as pd
import plotly.express as px
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df1 = df.melt(id_vars=['Date']+list(df.keys()[5:]), var_name='AAPL')
fig = px.line(df1, x='Date', y='value', color='AAPL' )
## remove date from each hovertemplate
for fig_data in fig.data:
fig_data['hovertemplate'] = fig_data['hovertemplate'].replace("<br>Date=%{x}","")
fig.update_layout(hovermode="x unified")
fig.show()
No, this doesn't work. There is an open issue for this:
https://github.com/plotly/plotly.js/issues/4755
And it doesn't seem that this will come soon. You have to decide between your way and something like:
import pandas as pd
import plotly.express as px
pio.templates.default = "plotly_white"
df_s = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df_s = df_s.melt(id_vars=["Date"]+list(df.keys()[5:]), var_name="AAPL")
fig = px.line(df_s, x="Date", y="value", color="AAPL")
fig.update_layout(
autosize=False,
width=1200,
height=800,
hovermode="x")
fig.show()
Output:

Plotly time series multiplots

I need help with plotly - plotting time series interactive charts with multiple lines in each subplot. My data looks like this:
import pandas as pd
df1 = pd.DataFrame(np.random.randint(100, size=(100,6)), columns=['A_red', 'A_blue', 'B_red', 'B_blue', 'C_red', 'C_blue'])
Next I want to do:
import plotly.express as px
fig1 = px.line(df, y=['A_red', 'A_blue'], color=['red', 'blue'])
fig2 = px.line(df, y=['B_red', 'B_blue'], color=['red', 'blue'])
fig3 = px.line(df, y=['C_red', 'C_blue'], color=['red', 'blue'])
figs = [fig1, fig2, fig3]
figs.show()
I cant get any plot to load in spyder (inline or in the plots tab), also how do I map colors to different lines?
Thanks
Spyder doesn't support interactive graphs. You have 2 options to show the plots: either show them in a browser, or display them as static plots. To render them in a browser where they will be interactive:
import plotly.io as pio
pio.renderers.default = 'browser'
To render them in the Spyder plots pane as a static chart:
import plotly.io as pio
pio.renderers.default = 'svg'
You need to delete the color argument from the px.line() calls or it will throw an error. Given the way your data is formatted, you won't be able to easily use the color argument. To change the colors of the lines:
fig1 = px.line(df, y=['A_red', 'A_blue'])
fig1.data[0].line.color = 'green'
fig1.data[1].line.color = 'purple'
fig1.show()
Not that you asked for it, but in order to get
figs = [fig1, fig2, fig3]
figs.show()
to work, you will need to do the following:
figs = [fig1, fig2, fig3]
for fig in figs:
fig.show()
To plot all 3 in a single figure you will first need to transform the data from wide to long:
df = pd.DataFrame(np.random.randint(100, size=(100,6)),
columns=['A_red', 'A_blue', 'B_red', 'B_blue', 'C_red', 'C_blue'])
df['x'] = df.index
df_long = df.melt(id_vars='x', var_name='letter')
df_long['group'] = df_long.letter.str.split('_', expand=True)[1]
df_long['letter'] = df_long.letter.str.split('_', expand=True)[0]
Then you can do the following:
facet_fig = px.line(df_long, y='value', x='x', color='group', facet_row='letter')

Plotly: How to use the same colors for categories of two different plots?

I am trying to create two plots with the same colour scheme for the categories. However the plots use different colour schemas and it seems like I can't get my head around to fix this:
.
How can I force the plotly to use the same colors for both graphs? I’d greatly appreciate any help!
Image
Define a discrete color map. In code below: c = dict(zip(df["emotion"].unique(), px.colors.qualitative.G10))
import pandas as pd
import numpy as np
import plotly.express as px
# create some data
df = pd.DataFrame({"date":np.random.choice(pd.date_range("1-sep-2020","31-Dec-2020"),300),
"emotion":np.random.choice(["positive","negative","anticipation","fear","trust"], 300)}).sort_values("date")
# map emotions to a color
c = dict(zip(df["emotion"].unique(), px.colors.qualitative.G10))
# bar chart
px.bar(
df.groupby(["date", "emotion"], as_index=False)
.size()
.rename(columns={"size": "count"}),
x="date",
y="count",
color="emotion",
color_discrete_map=c
).show()
# pie chart
px.pie(
df.groupby("emotion", as_index=False).agg(
perc=("date", lambda s: len(s) / len(df))
),
values="perc",
names="emotion",
color="emotion",
color_discrete_map=c
).show()
The color_discrete_map property of plotly.express pie and bar chart can be used to set explicit color values for columns.
Example usage for Pie Chart:
import plotly.express as px
df = px.data.tips()
fig = px.pie(df, values='tip', names='day', color='day',
color_discrete_map={'Thur':'lightcyan',
'Fri':'cyan',
'Sat':'royalblue',
'Sun':'darkblue'})
fig.show()
Example usage for Bar Chart:
import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.bar(df, y="continent", x="pop", color="continent", orientation="h", hover_name="country",
color_discrete_map={
"Europe": "red",
"Asia": "green",
"Americas": "blue",
"Oceania": "goldenrod",
"Africa": "magenta"},
title="Explicit color mapping")
fig.show()

I want to specify a color in plotly [duplicate]

This question already has an answer here:
Plotly: How to define colors in a figure using Plotly Graph Objects and Plotly Express?
(1 answer)
Closed 1 year ago.
I want to use plotly to specify the color.
However, with the current code, using marker=dict(color=colors) will naturally result in an error.
How can I specify the type and also the color at the same time?
import plotly.express as px
fig = px.scatter(
df,
x=x_axis,
y=y_axis,
color="species",
)
fig.show()
As an image, I want to specify something like this. color is a list, and it contains the same kind of data as species.
import seaborn as sns
def get_colorpalette(colorpalette, file_number):
palette = sns.color_palette(
colorpalette, file_number)
rgb = ['rgb({},{},{},{})'.format(*[x*256 for x in rgb],1)
for rgb in palette]
return rgb
colors = get_colorpalette('hls', graphNumber)
fig = px.scatter(
df,
x=x_axis,
y=y_axis,
color="species",
marker=dict(color=colors)
)
fig.show()
postscript
I have prepared color in RGB, but it would be nice if I could specify the color in RGB in plotly.
The following is an example of how to specify a color in plotly.
import numpy as np
import seaborn as sns
import plotly.graph_objs as go
import plotly.offline as py
import plotly
def get_colorpalette(colorpalette, n_colors):
palette = sns.color_palette(
colorpalette, n_colors)
rgb = ['rgb({},{},{})'.format(*[x*256 for x in rgb])
for rgb in palette]
return rgb
n_legends = 12
x = np.arange(0, 1, .01)
y = np.random.rand(n_legends, 100) + \
np.arange(n_legends).reshape(-1, 1)
colors = get_colorpalette('hls', n_legends)
data = [
go.Scatter(
x=x, y=y[i], name='凡例 {:02d}'.format(i),
marker={'color':colors[i]})
for i in range(n_legends)]
fig = go.Figure(data=data)
py.iplot(fig)
Arbitrary color settings can be made with the following settings See this page for details. The following code was taken from the sample in the official reference.
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df,
x="sepal_width",
y="sepal_length",
color="species",
size='petal_length',
hover_data=['petal_width'],
color_discrete_sequence=["blue", "goldenrod", "magenta"])
fig.show()
By default, Plotly Express will use the color sequence from the active template's layout. colorway attribute, and the default active template is plotly which uses the plotly color sequence. You can choose any of the following built-in qualitative color sequences from the px. colors.

Categories