Plotly Funnel Chart Example Shows Zero Width Shapes - python

I have copied and pasted the exact code on the plotly example page here in a Jupyter notebook - with the exception that I am running in offline mode so my import statements look like this:
from plotly.offline import init_notebook_mode
import plotly.offline as py
import plotly.figure_factory as ff
from plotly import graph_objs as go
init_notebook_mode()
The resulting plot has funnel shapes with no width.
Is the example code broken? I thought it had something to do with defining the shape and path variables, but printing those values they look reasonable.
Or, seems unlikely, but could offline mode be messing something up?
Complete code from the linked example is below:
values = [13873, 10553, 5443, 3703, 1708]
phases = ['Visit', 'Sign-up', 'Selection', 'Purchase', 'Review']
colors = ['rgb(32,155,160)', 'rgb(253,93,124)', 'rgb(28,119,139)', 'rgb(182,231,235)', 'rgb(35,154,160)']
n_phase = len(phases)
plot_width = 400
section_h = 100
section_d = 10
unit_width = plot_width / max(values)
phase_w = [int(value * unit_width) for value in values]
height = section_h * n_phase + section_d * (n_phase - 1)
shapes = []
label_y = []
for i in range(n_phase):
if (i == n_phase-1):
points = [phase_w[i] / 2, height, phase_w[i] / 2, height - section_h]
else:
points = [phase_w[i] / 2, height, phase_w[i+1] / 2, height - section_h]
path = 'M {0} {1} L {2} {3} L -{2} {3} L -{0} {1} Z'.format(*points)
shape = {
'type': 'path',
'path': path,
'fillcolor': colors[i],
'line': {
'width': 1,
'color': colors[i]
}
}
shapes.append(shape)
# Y-axis location for this section's details (text)
label_y.append(height - (section_h / 2))
height = height - (section_h + section_d)
# For phase names
label_trace = go.Scatter(
x=[-350]*n_phase,
y=label_y,
mode='text',
text=phases,
textfont=dict(
color='rgb(200,200,200)',
size=15
)
)
# For phase values
value_trace = go.Scatter(
x=[350]*n_phase,
y=label_y,
mode='text',
text=values,
textfont=dict(
color='rgb(200,200,200)',
size=15
)
)
data = [label_trace, value_trace]
layout = go.Layout(
title="<b>Funnel Chart</b>",
titlefont=dict(
size=20,
color='rgb(203,203,203)'
),
shapes=shapes,
height=560,
width=800,
showlegend=False,
paper_bgcolor='rgba(44,58,71,1)',
plot_bgcolor='rgba(44,58,71,1)',
xaxis=dict(
showticklabels=False,
zeroline=False,
),
yaxis=dict(
showticklabels=False,
zeroline=False
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig)

Related

Is it possibile to optimize Plotly carpet rendering?

I am working on a plotter for Finite Element Method solutions. I decided to use the Plotly library because of the carpet plots. I have my data to plot and this is my result:
Flow over NACA0012
Each element is represented as a Carpet, and for each carpet the solution is shown as a Countourcarpet. Everything is in place, but the rendering is too slow and the interactive interface is therefore nearly useless. Is there a way to enhance the performance of the rendering? I have read about different renderers in Plotly, but the plot just does not open. Is there a a way to speed up the rendering? Surely I will have to manage larger dataset. In this example I am using 740 carpets.
These are the Contourcarpet settings:
fig.add_trace(go.Contourcarpet(
a = a,
b = b,
z = u, # Sution correspondent at (a,b) parametric location
showlegend = showLegendFlag,
name = "Density",
legendgroup = "Density",
autocolorscale = False,
colorscale = "Inferno",
autocontour = False,
carpet = str(e), # The carpet on which to plot the solution is
# referenced as a string number
contours = dict(
start = start1, # Min value
end = end1, # Max value
size = abs(end1-start1) / countour_number, # Plot colour discretization
showlines = False
),
line = dict(
smoothing = 0
),
colorbar = dict(
len = 0.4,
y = 0.25
)
))
And these are the layout settings:
fig.update_layout(
plot_bgcolor="#FFF",
yaxis = dict(
zeroline = False,
range = [-1.800,1.800],
showgrid = False
),
dragmode = "pan",
height = 700,
xaxis = dict(
zeroline = False,
scaleratio = 1,
scaleanchor = 'y',
range = [-3.800,3.800],
showgrid = False
),
title = "Flow over NACA 0012",
hovermode = "closest",
margin = dict(
r = 80,
b = 40,
l = 40,
t = 80
),
width = 900
)
fig.show()

Python plotly Scattermapbox define colors by category

I want to draw some colored areas on a map. The coordinates are defined in a dataframe and I want each area to have a different color depending on the test_type value.
How can I do this? (Question is similar to a previous unanswered post)
import numpy as np
import pandas as pd
import plotly.graph_objects as go
# my test dataset
df = pd.DataFrame(data={'names':['area1','area2','area3'], 'coords': 0})
df['coords'] = df['coords'].astype(object)
df.at[0,'coords'] = [[-73.606352888, 45.507489991], [-73.606133883, 45.50687600], [-73.617533258, 45.527512253], [-73.618074188, 45.526759105], [-73.618271651, 45.526500673], [-73.618446320, 45.526287943], [-73.620201713, 45.524298907], [-73.620775593, 45.523650879]]
df.at[1,'coords'] = [[-73.706352888, 45.507489991], [-73.706133883, 45.50687600], [-73.717533258, 45.527512253], [-73.718074188, 45.526759105], [-73.718271651, 45.526500673], [-73.718446320, 45.526287943], [-73.720201713, 45.524298907], [-73.720775593, 45.523650879]]
df.at[2,'coords'] = [[-73.606352888, 45.497489991], [-73.606133883, 45.49687600], [-73.617533258, 45.517512253], [-73.618074188, 45.516759105], [-73.618271651, 45.516500673], [-73.618446320, 45.516287943], [-73.620201713, 45.514298907], [-73.620775593, 45.513650879]]
df['test_type'] = ['alpha','beta','beta']
def get_close_coords(coords):
# points must define a closed area
c = np.zeros((len(coords) + 1, 2))
c[:-1, :] = coords
c[-1, :] = c[0, :]
return c
fig = go.Figure(go.Scattermapbox(mode = "markers", lon = [-73.605], lat = [45.51]))
for i, c in enumerate(df.coords):
coords = get_close_coords(c)
fig.add_trace(go.Scattermapbox(lat=coords[:, 1], lon=coords[:, 0], color=df.test_type[i], mode="lines", fill="toself", name="Area %s" % i, opacity=0.4))
fig.update_layout(
mapbox = {
'style': "stamen-terrain",
'center': {'lon': -73.6, 'lat': 45.5},
'zoom': 12,
'color': df.test_type,
},
margin = {'l':0, 'r':0, 'b':0, 't':0})
fig.show()
First, the color setting is not simply a color specification, but a marker attribute, which is set by the marker specification in the scattermapbox. Then the color value must be an rgb value, hex color value, or color name. For this purpose, a column of colors to be referenced is added to the original data.
fig = go.Figure(go.Scattermapbox(mode="markers", lon=[-73.605], lat=[45.51]))
for i, c in enumerate(df.coords):
coords = get_close_coords(c)
fig.add_trace(go.Scattermapbox(lat=[x[1] for x in coords],
lon=[x[0] for x in coords],
mode="lines",
marker=go.scattermapbox.Marker(
color=df.test_type_color[i]
),
fill="toself",
name="Area %s" % i,
opacity=0.4
))
fig.update_layout(
mapbox = {
'style': "stamen-terrain",
'center': {'lon': -73.6, 'lat': 45.5},
'zoom': 11,
#'color': df.test_type,
},
margin = {'l':0, 'r':0, 'b':0, 't':0})
fig.show()

3D animation of time series in Plotly

I'm prototyping some code to then bring in some more complex time series data (and a lot of it) but can't for the life of me figure out how to get the vector components to animate in the below code. The blue path looks good to start with then disappears on play. And secondly, only the x component displays on play. I've been working mostly off the tutorials on the main plotly site so far, but, as the project builds complexity, my lack of expertise in plotly has let me down. I'm developing in an online Jupyter notebook if someone has any suggestions on how to make my code better. Thanks.
N = 50
vec_x, vec_y, vec_z = [0,0,0]
list_of_lists = []
choice = [-0.2, 0.2]
for i in range(N):
vec_x = vec_x + np.random.choice(choice)
vec_y = vec_y + np.random.choice(choice)
vec_z = vec_z + np.random.choice(choice)
list_of_lists.append([vec_x, vec_y, vec_z])
points = np.array(list_of_lists)
source = points.T
def frameMaker(i):
"""
returns x,y,z dict of currently indexed frame by vector component key
"""
scale = 10
list_of_lists = dict({
"x": [[source[0][i],scale * source[0][i+1]], [source[1][i],source[1][i]], [source[2][i],source[2][i]]],
"y": [[source[0][i],source[0][i]], [source[1][i],scale * source[1][i+1]], [source[2][i], source[2][i]]],
"z": [[source[0][i],source[0][i]], [source[1][i],source[1][i]], [source[2][i], scale * source[2][i+1]]]
})
return list_of_lists
#graphics
plt = go.Figure(
data=[go.Scatter3d(
x=source[0],
y=source[1],
z=source[2],
mode="lines",
line=dict(
color="darkblue",
width=2)),
go.Scatter3d(
x=source[0],
y=source[1],
z=source[2],
mode="lines",
line=dict(
color="darkblue",
width=2))
],
layout =
go.Layout(
title = go.layout.Title(text="Title | Total Frames: "+ str(N)),
scene_aspectmode="cube",
scene = dict(
xaxis = dict(range=[-2,2], nticks=10, autorange=False),
yaxis = dict(range=[-2,2], nticks=10, autorange=False),
zaxis = dict(range=[-2,2], nticks=10, autorange=False)),
updatemenus=[dict(type="buttons",
buttons=[dict(label="Play",
method="animate",
args=[None])])]
),
frames=[go.Frame(
data=[go.Scatter3d(
x = [source[0][k]],
y = [source[1][k]],
z = [source[2][k]],
mode="markers",
marker=dict(color="red",size=10,opacity=0.5)),
go.Scatter3d(
x=frameMaker(k)["x"][0],
y=frameMaker(k)["x"][1],
z=frameMaker(k)["x"][2],
line=dict(color='darkblue',width=2)),
go.Scatter3d(
x=frameMaker(k)["y"][0],
y=frameMaker(k)["y"][1],
z=frameMaker(k)["y"][2],
line=dict(color='#bcbd22',width=2)),
go.Scatter3d(
x=frameMaker(k)["z"][0],
y=frameMaker(k)["z"][1],
z=frameMaker(k)["z"][2],
line=dict(color='#d62728',width=2))],
layout=go.Layout(
title = go.layout.Title(text=str([k+1,list(map(lambda x: round(x,3), source.T[k]))]))
)
) for k in range(N-1)
]
)
plt.show()

Customizing a Networkx graph (or Scatter) with Python Plotly

I'm using Plotly's Python interface to generate a network. I've managed to create a network with my desired nodes and edges, and to control the size of the nodes.
I am desperately looking for help on how to do the following:
add node labels
add edge labels according to a list of weights
control the edge line width according to a list of weights
All this without using the "hovering" option, as it has to go in a non-interactive paper. I'd greatly appreciate any help! Plotly's output |
In case this fails, the figure itself |
matrix.csv
This is my code (most is copy-pasted from the Plotly tutorial for Networkx):
import pandas as pd
import plotly.plotly as py
from plotly.graph_objs import *
import networkx as nx
matrix = pd.read_csv("matrix.csv", sep = "\t", index_col = 0, header = 0)
G = nx.DiGraph()
# add nodes:
G.add_nodes_from(matrix.columns)
# add edges:
edge_lst = [(i,j, matrix.loc[i,j])
for i in matrix.index
for j in matrix.columns
if matrix.loc[i,j] != 0]
G.add_weighted_edges_from(edge_lst)
# create node trace:
node_trace = Scatter(x = [], y = [], text = [], mode = 'markers',
marker = Marker(
showscale = True,
colorscale = 'YIGnBu',
reversescale = True,
color = [],
size = [],
colorbar = dict(
thickness = 15,
title = 'Node Connections',
xanchor = 'left',
titleside = 'right'),
line = dict(width = 2)))
# set node positions
pos = nx.spring_layout(G)
for node in G.nodes():
G.node[node]['pos']= pos[node]
for node in G.nodes():
x, y = G.node[node]['pos']
node_trace['x'].append(x)
node_trace['y'].append(y)
# create edge trace:
edge_trace = Scatter(x = [], y = [], text = [],
line = Line(width = [], color = '#888'),
mode = 'lines')
for edge in G.edges():
x0, y0 = G.node[edge[0]]['pos']
x1, y1 = G.node[edge[1]]['pos']
edge_trace['x'] += [x0, x1, None]
edge_trace['y'] += [y0, y1, None]
edge_trace['text'] += str(matrix.loc[edge[0], edge[1]])[:5]
# size nodes by degree
deg_dict = {deg[0]:int(deg[1]) for deg in list(G.degree())}
for node, degree in enumerate(deg_dict):
node_trace['marker']['size'].append(deg_dict[degree] + 20)
fig = Figure(data = Data([edge_trace, node_trace]),
layout = Layout(
title = '<br>AA Substitution Rates',
titlefont = dict(size = 16),
showlegend = True,
margin = dict(b = 20, l = 5, r = 5, t = 40),
annotations = [dict(
text = "sub title text",
showarrow = False,
xref = "paper", yref = "paper",
x = 0.005, y = -0.002)],
xaxis = XAxis(showgrid = False,
zeroline = False,
showticklabels = False),
yaxis = YAxis(showgrid = False,
zeroline = False,
showticklabels = False)))
py.plot(fig, filename = 'networkx')
So
1. The solution to this is relative easy, you create a list with the node ids and you set it in the text attribute of the scatter plot. Then you set the mode as "markers+text" and you're done.
2. This is a little bit more tricky. You have to calculate the middle of each line and create a list of dicts including the line's middle position and weight. Then you add set as the layout's annotation.
3. This is too compicated to be done using plotly IMO. As for now I am calculating the position of each node using networkx spring_layout function. If you'd want to set the width of each line based on its weight you would have to modify the position using a function that takes into account all the markers that each line is attached to.
Bonus I give you the option to color each of the graph's components differently.
Here's a (slightly modified) function I made a while ago that does 1 and 2:
import pandas as pd
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import networkx as nx
def scatter_plot_2d(G, folderPath, name, savePng = False):
print("Creating scatter plot (2D)...")
Nodes = [comp for comp in nx.connected_components(G)] # Looks for the graph's communities
Edges = G.edges()
edge_weights = nx.get_edge_attributes(G,'weight')
labels = [] # names of the nodes to plot
group = [] # id of the communities
group_cnt = 0
print("Communities | Number of Nodes")
for subgroup in Nodes:
group_cnt += 1
print(" %d | %d" % (group_cnt, len(subgroup)))
for node in subgroup:
labels.append(int(node))
group.append(group_cnt)
labels, group = (list(t) for t in zip(*sorted(zip(labels, group))))
layt = nx.spring_layout(G, dim=2) # Generates the layout of the graph
Xn = [layt[k][0] for k in list(layt.keys())] # x-coordinates of nodes
Yn = [layt[k][1] for k in list(layt.keys())] # y-coordinates
Xe = []
Ye = []
plot_weights = []
for e in Edges:
Xe += [layt[e[0]][0], layt[e[1]][0], None]
Ye += [layt[e[0]][1], layt[e[1]][1], None]
ax = (layt[e[0]][0]+layt[e[1]][0])/2
ay = (layt[e[0]][1]+layt[e[1]][1])/2
plot_weights.append((edge_weights[(e[0], e[1])], ax, ay))
annotations_list =[
dict(
x=plot_weight[1],
y=plot_weight[2],
xref='x',
yref='y',
text=plot_weight[0],
showarrow=True,
arrowhead=7,
ax=plot_weight[1],
ay=plot_weight[2]
)
for plot_weight in plot_weights
]
trace1 = go.Scatter( x=Xe,
y=Ye,
mode='lines',
line=dict(color='rgb(90, 90, 90)', width=1),
hoverinfo='none'
)
trace2 = go.Scatter( x=Xn,
y=Yn,
mode='markers+text',
name='Nodes',
marker=dict(symbol='circle',
size=8,
color=group,
colorscale='Viridis',
line=dict(color='rgb(255,255,255)', width=1)
),
text=labels,
textposition='top center',
hoverinfo='none'
)
xaxis = dict(
backgroundcolor="rgb(200, 200, 230)",
gridcolor="rgb(255, 255, 255)",
showbackground=True,
zerolinecolor="rgb(255, 255, 255)"
)
yaxis = dict(
backgroundcolor="rgb(230, 200,230)",
gridcolor="rgb(255, 255, 255)",
showbackground=True,
zerolinecolor="rgb(255, 255, 255)"
)
layout = go.Layout(
title=name,
width=700,
height=700,
showlegend=False,
plot_bgcolor="rgb(230, 230, 200)",
scene=dict(
xaxis=dict(xaxis),
yaxis=dict(yaxis)
),
margin=dict(
t=100
),
hovermode='closest',
annotations=annotations_list
, )
data = [trace1, trace2]
fig = go.Figure(data=data, layout=layout)
plotDir = folderPath + "/"
print("Plotting..")
if savePng:
plot(fig, filename=plotDir + name + ".html", auto_open=True, image = 'png', image_filename=plotDir + name,
output_type='file', image_width=700, image_height=700, validate=False)
else:
plot(fig, filename=plotDir + name + ".html")
The d3graph library provides the functionalities you want.
pip install d3graph
I downloaded your data and imported it for demonstration:
# Import data
df = pd.read_csv('data.csv', index_col=0)
# Import library
from d3graph import d3graph
# Convert your Pvalues. Note that any edge is set when a value in the matrix is >0. The edge width is however based on this value. A conversion is therefore useful when you work with Pvalues.
df[df.values==0]=1
df = -np.log10(df)
# Increase some distance between edges. Maybe something like this.
df = (np.exp(df)-1)/10
# Make the graph with default settings
d3 = d3graph()
# Make the graph by setting some parameters
d3.graph(df)
# Set edge properties
d3.set_edge_properties(directed=True)
# Set node properties
d3.set_node_properties(color=df.columns.values, size=size, edge_size=10, edge_color='#000000', cmap='Set2')
This will result in an interactive network graph. Two screenshots: one with the default settings and the one with tweaked settings. More examples can be found here.

Jupyter Notebook not ploting output using plotly

I am working on choropleth using plotly in Jupyter Notebook.I want to plot choropleth but its showing me empty output.I am working with offline plotly.In html its genrated chart successfuly but when i tried offline it shows me empty output.please tell me how i solve this error.
here is my code
from plotly.graph_objs import *
from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
from plotly.offline.offline import _plot_html
init_notebook_mode(connected=True)
for col in state_df.columns:
state_df[col] = state_df[col].astype(str)
scl = [[0.0, 'rgb(242,240,247)'],[0.2, 'rgb(218,218,235)'],[0.4, 'rgb(188,189,220)'],\
[0.6, 'rgb(158,154,200)'],[0.8, 'rgb(117,107,177)'],[1.0, 'rgb(84,39,143)']]
state_df['text'] = state_df['StateCode'] + '<br>' +'TotalPlans '+state_df['TotalPlans']
data = [ dict(
type='choropleth',
colorscale = scl,
autocolorscale = False,
locations = state_df['StateCode'],
z = state_df['TotalPlans'].astype(float),
locationmode = 'USA-states',
text = state_df['text'],
marker = dict(
line = dict (
color = 'rgb(255,255,255)',
width = 2
)
),
colorbar = dict(
title = "Millions USD"
)
) ]
layout = dict(
title = 'Plan by States',
geo = dict(
scope='usa',
projection=dict( type='albers usa' ),
showlakes = True,
lakecolor = 'rgb(255, 255, 255)',
),
)
fig = dict(data=data, layout=layout)
plotly.offline.iplot(fig)
You are passing a dictionary to iplot which in contradiction to the documentation can handle only Figure objects and not dictionaries.
Try
fig = Figure(data=[data], layout=layout)
and it should work.

Categories

Resources