Python Plotly scatter 3D plot colormap customization - python

I am using plotly. I am getting the plot. The problem is, I am using seasons as colormap. I have used 1 for fall, 2 for winter, ..,4 for summer. Now, the colomap shows these numbers and also 1.5, 2.5 etc. I want to show Names instead of numbers
My code:
import plotly.express as px
from plotly.offline import plot
import plotly
fig = px.scatter_3d(df, x=xlbl, y=ylbl, z=zlbl,
color=wlbl,opacity=0,
color_continuous_scale = plotly.colors.sequential.Viridis)
temp_name = 'Temp_plot.html'
plot(fig, filename = temp_name, auto_open=False,
image_width=1200,image_height=800)
plot(fig)
Present output:

You can modify the coloraxis by adding the following lines to your code:
cat_labels = ["Fall", "Winter", "Spring", "Summer"]
fig.update_coloraxes(colorbar=dict(ticktext=cat_labels,
tickvals=list(range(1, len(cat_labels)+1))))
Sample output with random data:

Related

Outliers not showing up in plotly

Hi I am using this code to generate a boxplot:
However, it is not showing all the data points also not showing up the outliers on the top. I am using this code:
import plotly.express as px
fig = px.box(dataset, y= 'Report_used',hover_name='entity_name')
fig.show()
It needs to be like this:
How can I do this?
Thanks
import plotly.express as px
fig = px.box(dataset,
y= 'Report_used',
hover_name='entity_name',
points='all')
fig.update_traces(pointpos=0)
fig.show()
If you wanted all the points to be on the whisker line:
fig.update_traces(pointpos=0, jitter=0)

How do you put the x axis labels on the top of the heatmap created with seaborn? [duplicate]

This question already has answers here:
How to move labels from bottom to top without adding "ticks"
(2 answers)
How to have the axis ticks in both top and bottom, left and right of a heatmap
(2 answers)
Closed 4 months ago.
I have created a heatmap using the seaborn and matplotlib package in python, and while it is perfectly suited for my current needs, I really would prefer to have the labels on the x-axis of the heatmap to be placed at the top of the plot, rather than at the bottom (which seems to be its default).
So an abridged form of my data looks like this:
NP NP1 NP2 NP3 NP4 NP5
identifier
A1BG~P04217 -0.094045 0.012229 0.102279 1.319618 0.002383
A2M~P01023 -0.805089 -0.477339 -0.351341 0.089735 -0.473815
AARS1~P49588 0.081827 -0.099849 -0.287426 0.101588 0.136366
ABCB6~Q9NP58 0.109911 0.458039 -0.039325 -0.484872 1.905586
ABCC1~I3L4X2 -0.560155 0.580285 0.012868 0.291303 -0.407900
ABCC4~O15439 0.055264 0.138630 -0.204665 0.191241 0.304999
ABCE1~P61221 -0.510108 -0.059724 -0.233365 0.078956 -0.651327
ABCF1~Q8NE71 -0.348526 -0.135414 -0.390021 -0.190644 -0.276303
ABHD10~Q9NUJ1 0.237959 -2.060834 0.325901 -0.778036 -4.046345
ABHD11~Q8NFV4 0.294587 1.193258 -0.797294 -0.148064 -1.153391
And when I use the following code:
import seaborn as sns
import matplotlib as plt
fig, ax = plt.subplots(figsize=(10,30))
ax = sns.heatmap(df_example, annot=True, xticklabels=True)
I get this kind of plot:
https://imgpile.com/i/T3zPH1
I should note that the this plot was made from the abridged dataframe above, the actual dataframe has thousands of identifiers, making it very long.
But as you can see, the labels on the x axis only appear at the bottom. I have been trying to get them to appear on the top, but seaborn doesn't seem to allow this kind of formatting.
So I have also tried using plotly express, but while I solve the issue of placing my x-axis labels on top, I have been completely unable to format the heat map as I had before using seaborn. The following code:
import plotly.express as px
fig = px.imshow(df_example, width= 500, height=6000)
fig.update_xaxes(side="top")
fig.show()
yields this kind of plot: https://imgpile.com/i/T3zF42.
I have tried many times to reformat it using the documentation from plotly (https://plotly.com/python/heatmaps/), but I can't seem to get it to work. When one thing is fixed, another problem arises. I really just want to keep using the seaborn based code as above, and just fix the x-axis labels. I'm also happy to have the x-axis label at both the top and bottom of the plot, but I can't get that work presently. Can someone advise me on what to do here?
Ok, so I did a bit more research, and it turns out you can add the follow code with the seaborn approach:
plt.tick_params(axis='both', which='major', labelsize=10, labelbottom = False, bottom=False, top = False, labeltop=True)
If your data are stored into csv file, you can use this code:
import pandas as pd
import plotly.express as px
df = pd.read_csv("file.csv").round(2)
fig = px.imshow(df.iloc[:,1:],
y = df['identifier'],
text_auto=True, aspect="auto")
fig.show()
The data in the CSV file are in the following format:
identifier NP1 NP2 NP3 NP4 NP5
A1BG~P04217 -0.094045 0.012229 0.102279 1.319618 0.002383
A2M~P01023 -0.805089 -0.477339 -0.351341 0.089735 -0.473815
AARS1~P49588 0.081827 -0.099849 -0.287426 0.101588 0.136366
ABCB6~Q9NP58 0.109911 0.458039 -0.039325 -0.484872 1.905586
ABCC1~I3L4X2 -0.560155 0.580285 0.012868 0.291303 -0.407900
ABCC4~O15439 0.055264 0.138630 -0.204665 0.191241 0.304999
ABCE1~P61221 -0.510108 -0.059724 -0.233365 0.078956 -0.651327
ABCF1~Q8NE71 -0.348526 -0.135414 -0.390021 -0.190644 -0.276303
ABHD10~Q9NUJ1 0.237959 -2.060834 0.325901 -0.778036 -4.046345
ABHD11~Q8NFV4 0.294587 1.193258 -0.797294 -0.148064 -1.153391
Now let's display the xaxis top of the heatmap by adding:
fig.update_layout(xaxis = dict(side ="top"))
Alternative solution if you have old version of Plotly:
fig = go.Figure(data=go.Heatmap(
x=df.columns[1:],
y=df.identifier,
z=df.iloc[:,1:],
text=df.iloc[:,1:],
texttemplate="%{text}"))
fig.update_layout(xaxis = dict(side ="top"))
fig.show()

Python Plotly Express Scatter Plot

I want to create an interactive scatter plot; so I am using the plotly.graph_objects module.
My data has two columns of about 100 points.
When I make a line plot, I have no problem.
But when I try to make a scatter plot, Jupyter seems to hang (message at the bottom says - Local Host not responding)
It takes a while for Jupyter to respond and I still have no plot.
The code I am using is:
import plotly.express as px
import plotly.graph_objects as go
fig = go.Figure()
var_list = ['cloxth1 ()','cloxth2 ()']
for item in var_list:
stripped_item = item.replace(' ()','')
fig.add_trace(go.Scatter(
x=np.linspace(0,len(df),len(df)),
y=df[item],
mode='markers',
marker={'size':1},
name = item
))
fig.update_layout(title = 'CLOXTH',
xaxis_title = 'data samples',
yaxis_title = 'mV')
fig.show()
Is there anything wrong with the way I am using go.Scatter?
I tried using px.scatter instead. It seems to work, as in I get a scatter plot. But in the plotly.express case I am unable to have a proper legend for 'cloxth1' and 'cloxth2'; also, both data sets are plotted with the same color.
How can I get around this?
A few rows from the data:
Sample Data
# read in with
df = pd.read_clipboard(sep=',', index_col=[0])
# copy to clipboard
,time(s),Filename,time_stamp,time_vector(ms),time_vector_zerobased(ms),cloxth1(),cloxth2()
0.0,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:03.8,0,0,725.9097285,725.9097285
1.001,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:04.8,1001,1001,725.9097285,725.9097285
2.001,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:05.8,2001,2001,725.9097285,725.9097285
3.002,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:06.8,3002,3002,725.9097285,725.9097285
4.0,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:07.8,4000,4000,725.9097285,725.9097285
5.002,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:08.8,5002,5002,725.9097285,725.9097285
6.002,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:09.8,6002,6002,725.9097285,725.9097285
7.001,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:10.8,7001,7001,725.9097285,725.9097285
8.003,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:11.8,8003,8003,725.9097285,725.9097285
9.002,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:12.8,9002,9002,725.9097285,725.9097285
10.0,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:13.8,10000,10000,725.9097285,725.9097285
11.005,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:14.8,11005,11005,725.9097285,725.9097285
12.0,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:15.8,12000,12000,725.9097285,725.9097285
13.001,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:16.8,13001,13001,725.9097285,725.9097285
14.003,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:17.8,14003,14003,725.9097285,725.9097285
15.0,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:18.8,15000,15000,725.9097285,725.9097285
16.002,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:19.8,16002,16002,725.9097285,725.9097285
17.0,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:20.8,17000,17000,725.9097285,725.9097285
18.0,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:21.8,18000,18000,725.9097285,725.9097285
19.003,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:22.8,19003,19003,725.9097285,725.9097285
20.001,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:23.8,20001,20001,725.9097285,725.9097285
21.0,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:24.8,21000,21000,725.9097285,725.9097285
22.005,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:25.8,22005,22005,725.9097285,725.9097285
23.0,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:26.8,23000,23000,725.9097285,725.9097285
24.002,4DRBUP1N8HB706662_Trip-Detail_2020-07-20,00-04-03.csv.zip,04:27.8,24002,24002,725.9097285,725.9097285

Plotly: How do I remove vertical lines that appear after introducing gaps in annotated heatmap?

When I introduce gaps in between bricks in a plotly annotated heatmap, vertical black lines appear behind the bricks (visible in the gaps). The lines appear to line up with the x-axis labels. Even more oddly, if the x-axis category is numeric, the label "0" will not get a vertical line. I want the vertical lines removed. I've looked at the documentation and can't figure out what these lines are. You'll notice that there are also horizontal vertical and white lines that line up with the x- and y-axis labels. I don't mind those.
import plotly.graph_objs as go
from plotly.figure_factory import create_annotated_heatmap
import numpy as np
fig = go.Figure(create_annotated_heatmap(z = np.arange(12).reshape(3,4),
x = [0,1,2,3],
y = ['A','B','C'],
xgap = 30, ygap = 30
)
)
fig.update_layout(title = 'What are these vertical lines?')
fig.show()
This is not an issue with the standard heatmap:
fig2 = go.Figure(go.Heatmap(z = np.arange(12).reshape(3,4),
x = [0,1,2,3],
y = ['A','B','C'],
xgap = 30, ygap = 30
)
)
fig2.update_layout(title = 'No vertical lines here.')
fig2.show()
Regarding the documentation from help(create_annotated_heatmap), there is a short list of parameters that don't seem to have anything to do with it, and kwargs that go through the standard plotly Heatmap.
The line under the zero is the 'zeroline' while the other lines are the 'gridlines'. They can be removed by setting zeroline=False and showgrid=False in the figure layout.
import plotly.graph_objs as go
from plotly.figure_factory import create_annotated_heatmap
import numpy as np
fig = go.Figure(create_annotated_heatmap(z=np.arange(12).reshape(3,4),
x=[0,1,2,3],
y=['A','B','C'],
xgap=30, ygap=30))
fig.update_layout(xaxis=dict(zeroline=False, showgrid=False),
yaxis=dict(zeroline=False, showgrid=False))
fig.show()
Alternatively, you can change their color to white as in the standard heatmap.
import plotly.graph_objs as go
from plotly.figure_factory import create_annotated_heatmap
import numpy as np
fig = go.Figure(create_annotated_heatmap(z=np.arange(12).reshape(3,4),
x=[0,1,2,3],
y=['A','B','C'],
xgap=30, ygap=30))
fig.update_layout(xaxis=dict(zeroline=False, gridcolor='white'),
yaxis=dict(zeroline=False, gridcolor='white'))
fig.show()

Plotly: How to make a 3D stacked histogram?

I have several histograms that I succeded to plot using plotly like this:
fig.add_trace(go.Histogram(x=np.array(data[key]), name=self.labels[i]))
I would like to create something like this 3D stacked histogram but with the difference that each 2D histogram inside is a true histogram and not just a hardcoded line (my data is of the form [0.5 0.4 0.5 0.7 0.4] so using Histogram directly is very convenient)
Note that what I am asking is not similar to this and therefore also not the same as this. In the matplotlib example, the data is presented directly in a 2D array so the histogram is the 3rd dimension. In my case, I wanted to feed a function with many already computed histograms.
The snippet below takes care of both binning and formatting of the figure so that it appears as a stacked 3D chart using multiple traces of go.Scatter3D and np.Histogram.
The input is a dataframe with random numbers using np.random.normal(50, 5, size=(300, 4))
We can talk more about the other details if this is something you can use:
Plot 1: Angle 1
Plot 2: Angle 2
Complete code:
# imports
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
pio.renderers.default = 'browser'
# data
np.random.seed(123)
df = pd.DataFrame(np.random.normal(50, 5, size=(300, 4)), columns=list('ABCD'))
# plotly setup
fig=go.Figure()
# data binning and traces
for i, col in enumerate(df.columns):
a0=np.histogram(df[col], bins=10, density=False)[0].tolist()
a0=np.repeat(a0,2).tolist()
a0.insert(0,0)
a0.pop()
a1=np.histogram(df[col], bins=10, density=False)[1].tolist()
a1=np.repeat(a1,2)
fig.add_traces(go.Scatter3d(x=[i]*len(a0), y=a1, z=a0,
mode='lines',
name=col
)
)
fig.show()
Unfortunately you can't use go.Histogram in a 3D space so you should use an alternative way. I used go.Scatter3d and I wanted to use the option to fill line doc but there is an evident bug see
import numpy as np
import plotly.graph_objs as go
# random mat
m = 6
n = 5
mat = np.random.uniform(size=(m,n)).round(1)
# we want to have the number repeated
mat = mat.repeat(2).reshape(m, n*2)
# and finally plot
x = np.arange(2*n)
y = np.ones(2*n)
fig = go.Figure()
for i in range(m):
fig.add_trace(go.Scatter3d(x=x,
y=y*i,
z=mat[i,:],
mode="lines",
# surfaceaxis=1 # bug
)
)
fig.show()

Categories

Resources