How do I remove the numbers and ticks from the internal y-axis in the Plot.ly heatmap subplot graph below? Both plots share the same y-axis range so there is no reason to show both.
import plotly.plotly as py
import plotly.graph_objs as go
from plotly import tools
import pandas as pd
import numpy as np
dfl = []
dfl.append(pd.DataFrame(np.random.random((100,100,))))
dfl.append(pd.DataFrame(np.random.random((100,100,))))
fig = tools.make_subplots(rows=1, cols=len(dfl) ,print_grid=False);
for index, a in enumerate(dfl):
sn = str(index)
data = go.Heatmap(
z=a.values.tolist(),
colorscale='Viridis',
colorbar=dict(title='units'),
)
fig.append_trace(data, 1, index+1)
fig['layout']['xaxis'+str(index+1)].update(title='xaxis '+str(index))
fig['layout']['yaxis1'].update(title='y-axis')
fig['layout'].update(height=600, width=800, title='heatmap subplots')
py.iplot(fig)
Simply pass the setting 'shared_yaxes=True' to the tools.make_subplots function call, that is:
fig = tools.make_subplots(rows=1, cols=len(dfl) ,print_grid=False, shared_yaxes=True)
Updated answer for newer versions of Plotly. Based upon the v4 migration guide.
Differences include
calling the make_subplots function from the plotly.subplots library, instead of plotly.tools, and
using fig.show inplace of py.iplot to show the figure in Jupyter.
The code below was tested in Plotly version 5.1.0 using Jupyter Notebook.
import plotly
import plotly.graph_objs as go
import pandas as pd
import numpy as np
dfl = []
dfl.append(pd.DataFrame(np.random.random((100,100,))))
dfl.append(pd.DataFrame(np.random.random((100,100,))))
fig = plotly.subplots.make_subplots(rows=1, cols=len(dfl) ,print_grid=False, shared_yaxes=True);
for index, a in enumerate(dfl):
sn = str(index)
data = go.Heatmap(
z=a.values.tolist(),
colorscale='Viridis',
colorbar=dict(title='units'),
)
fig.append_trace(data, 1, index+1)
fig['layout']['xaxis'+str(index+1)].update(title='xaxis '+str(index))
fig['layout']['yaxis1'].update(title='y-axis')
fig['layout'].update(height=600, width=800, title='heatmap subplots')
fig.show()
The output:
Related
I would like to have a multiple line plot within same canvas tied with the same x-axis as shown something in the figure:
Using subplots does not achieve the intended desire.
import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go
fig = make_subplots(rows=2, shared_xaxes=True,vertical_spacing=0.1)
fig.add_scatter(y=[2, 1, 3], row=1, col=1)
fig.add_scatter(y=[1, 3, 2], row=2, col=1)
fig.show()
May I know how this can be done, appreciate if someone can point to good reading material
With a dataset such as this you can select any number of columns, set up a figure using fig = make_subplots() with shared_xaxes set to True and then add your series with a shared x-axis using fig.add_trace(go.Scatter(x=df[col].index, y=df[col].values), row=i, col=1) in a loop to get this:
Let me know if this is a setup you can use but need a little tweaking.
Complete code:
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 = df.set_index('Date')
df.tail()
cols = df.columns[:-4]
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[col].index, y=df[col].values), row=i, col=1)
fig.show()
Depending on the data you are plotting, I think you could either check out "Stacked Subplots with a Shared X-Axis (low-level API)" on https://plotly.com/python/subplots/
Or separate the data by shifting each line plot upwards like so:
import plotly.graph_objects as go
import random
data = []
n = 9
for x in range(10, 60, 10):
points = [value + x for value in random.sample(range(1,n+1), k = n)]
data.append(go.Scatter(y=points))
fig = go.Figure(data = data)
fig.show()
Trying to plot a very simple 3d scatter plot with x,y,z axes all equal in length. It is not working.
Code:
'''
from mpl_toolkits import mplot3d
import pandas
from pandas import DataFrame
pt_num = 100
x = np.random.uniform(-10,10,size=(pt_num,2))
model = np.array([2,2]).reshape(-1,1)
y = np.dot(x,model)
data = np.hstack((x,y))
dats = {'x':data[:,0].squeeze(),'w':data[:,1].squeeze(),'y':data[:,2].squeeze()}
df = DataFrame(data=dats)
import plotly.express as px
fig = px.scatter_3d(df, x='x', y='w', z='y',width=1200, height=1200)
fig.update_layout(scene=dict(xaxis=dict(range=[-10,10]),yaxis=dict(range=[-10,10]),zaxis=dict(range=[-10,10])))
fig['layout'].update(width=1500, height=1500, autosize=False)
fig.show()
'''
Thank you for any help.
Asked too soon out of frustration. The answer is to add 'aspectmode="cube"' to the scene dict for fig.update_layout:
fig.update_layout(scene=dict(xaxis=dict(range=view_range),yaxis=dict(range=view_range),zaxis=dict(range=view_range),aspectmode="cube"))
How to make x-axis of the following histogram, logarithmic?
The following code:
data_list = [1,1,5,5,5,100,100]
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Histogram(x=data_list, nbinsx=100))
import plotly.offline as py
py.init_notebook_mode(connected=False)
py.offline.plot(fig, filename = 'test.html')
Produces typical histogram.
How can I change the x-axis logarithmic?
I also tried:
data_list = [1,1,5,5,5,100,100]
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Histogram(x=data_list, nbinsx=100))
fig.update_layout(xaxis_type="log")
fig.update_xaxes(tick0=0, dtick=1, range=[0,2.5])
import plotly.offline as py
py.init_notebook_mode(connected=False)
py.offline.plot(fig, filename = 'test.html')
but this will result in non-logarithmic bins, and essentially, the bin at 100 disappears!
As said above in the comments, logarithmic axes are not possible with plotly. You could try to create bins using numpy and create a bar plot with those.
I have some matplotlib graphs that need to be viewed offline in a browser, I was using MPLD3 to render them before, but given the need to view the plots without an internet connection, I'm considering using plotly. Is there a way to view matplotlib plotly graphs offline?
A minimal example of converting a matplotlib figure to plotly would look like this.
import matplotlib.pyplot as plt
import plotly
import plotly.plotly as py
import plotly.tools as tls
fig, ax = plt.subplots()
ax.plot([1, 2, 3], [1, 4, 9], "o")
plotly_fig = tls.mpl_to_plotly(fig)
plotly.offline.plot(plotly_fig, filename="plotly version of an mpl figure")
Just posting this as the documentation was somewhat hard to follow.
import plotly.tools as tls
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
x = np.random.random(100) ### toy data
y = np.random.random(100) ### toy data
## matplotlib fig
fig, axes = plt.subplots(2,1, figsize = (10,6))
axes[0].plot(x, label = 'x')
axes[1].scatter(x,y)
## convert and plot in plotly
plotly_fig = tls.mpl_to_plotly(fig) ## convert
iplot(plotly_fig)
How about this page at Section Offline Use
BTW: You can also write a static image file as described here
import plotly.io as pio
import plotly.graph_objs as go
fig = go.Figure()
# Do some fig.add_scatter() stuff here
pio.write_image(fig, 'fig1.png')
If I create a horizontal bar graph using plotly, the labels for each bar are right up against the graph. I'd like to add some space/pad/margin between the label and the graph. How can I do this?
Example:
import plotly.offline as py
import plotly.graph_objs as go
labels = ['Alice','Bob','Carl']
vals = [2,5,4]
data = [go.Bar(x=vals, y=labels, orientation='h')]
fig = go.Figure(data)
py.iplot(fig)
Just use parameter pad in margin. Check example from docs here.
Code:
import plotly.offline as py
import plotly.graph_objs as go
labels = ['Alice','Bob','Carl']
vals = [2,5,4]
data = [go.Bar(x=vals, y=labels, orientation='h')]
layout = go.Layout(
margin=dict(
pad=20
),
title = 'hbar',
)
fig = go.Figure(data=data,layout=layout)
py.plot(fig, filename='horizontal-bar.html')
And plot should be looks something like that:
Shorter solution:
fig.update_layout(margin_pad=10)
I think you could add some code like this.
import plotly.offline as py
import plotly.graph_objs as go
labels = ['Alice','Bob','Carl']
vals = [2,5,4]
data = [go.Bar(x=vals, y=labels, orientation='h')]
layout = dict(yaxis=dict(ticksuffix=" "))
fig = go.Figure(data=data,layout=layout)
py.iplot(fig)
add a suffix will fix this problem easily. I have checked the reference plotly ref, it also have more suitable key named tickformat, but it hard to use so I didn't use it.