Plotly Python - Change font of table - python

I have a table that I produced in plotly, and I want to change the font to 'Gill Sans'.
I am having trouble making it change. Is this possible?
This is my code:
groupA = new_df.groupby('Call').agg({'TotalGrantValue':sum, 'FirstReceivedDate':'count'}).rename(columns={'FirstReceivedDate':'Count'})
groupA['TotalGrantValue'] = groupA['TotalGrantValue'].map('{:,.2f}'.format)
colorscale = [[0, '#7f7f7f'],[.5, '#F1EDED'],[1, '#ffffff']]
table = ff.create_table(groupA, index=True,colorscale=colorscale, height_constant=14, index_title='Date')
table.layout.width = 700
for i in range(len(table.layout.annotations)):
table.layout.annotations[i].font.size = 10
plotly.offline.iplot(table, config={"displayModeBar": False}, show_link=False, filename='index_table_pd')

You need to define a layout parameter as stated in https://plot.ly/python/axes/.
from the same page, there is an example code that should help you:
layout = go.Layout(
xaxis=dict(
title='AXIS TITLE',
titlefont=dict(
family='Arial, sans-serif',
size=18,
color='lightgrey'
),
showticklabels=True,
tickangle=45,
tickfont=dict(
family='Old Standard TT, serif',
size=14,
color='black'
),
exponentformat='e',
showexponent='All'
),
yaxis=dict(
title='AXIS TITLE',
titlefont=dict(
family='Arial, sans-serif',
size=18,
color='lightgrey'
),
showticklabels=True,
tickangle=45,
tickfont=dict(
family='Old Standard TT, serif',
size=14,
color='black'
),
exponentformat='e',
showexponent='All'
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='axes-labels')

Related

How to make a plotly graph wider and higher? [duplicate]

I have made a scatter plot using matplotlib and Plotly. I want the height, width and the markers to be scatter as in matplotlib plot. Please see the attached plots.
I used the following code in Plotly
import plotly
import plotly.plotly as py
from plotly.graph_objs import Scatter
import plotly.graph_objs as go
trace1 = go.Scatter(
x=x1_tsne, # x-coordinates of trace
y=y1_tsne, # y-coordinates of trace
mode='markers ', # scatter mode (more in UG section 1)
text = label3,
opacity = 1,
textposition='top center',
marker = dict(size = 25, color = color_4, symbol = marker_list_2, line=dict(width=0.5)),
textfont=dict(
color='black',
size=18, #can change the size of font here
family='Times New Roman'
)
)
layout = {
'xaxis': {
'showticklabels': False,
'showgrid': False,
'zeroline': False,
'linecolor':'black',
'linewidth':2,
'mirror':True,
'autorange':False,
'range':[-40, 40][![enter image description here][1]][1]
},
'yaxis': {
'showticklabels': False,
'showgrid': False,
'zeroline': False,
'linecolor':'black',
'linewidth':2,
'mirror':True,
'autorange':False,
'range':[-40, 40]
}
}
data = [trace1]
fig = go.Figure(
data= data,
layout= layout)
py.iplot(fig)
I try to tune the range but did not help. In addition, I use Autorange that did not help. Could you please help me with this.
I want the image as
##update: This can be done by the following code. I am updating this in the question:
trace1 = go.Scatter(
x=x1_tsne, # x-coordinates of trace
y=y1_tsne, # y-coordinates of trace
mode='markers +text ', # scatter mode (more in UG section 1)
text = label3,
opacity = 1,
textposition='top center',
marker = dict(size = 25, color = color_4, symbol = marker_list_2, line=dict(width=0.5)),
textfont=dict(
color='black',
size=18, #can change the size of font here
family='Times New Roman'
)
)
data = [trace1]
layout = go.Layout(
autosize=False,
width=1000,
height=1000,
xaxis= go.layout.XAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
yaxis= go.layout.YAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
margin=go.layout.Margin(
l=50,
r=50,
b=100,
t=100,
pad = 4
)
)
fig = go.Figure(data=data, layout=layout)
py.iplot(fig, filename='size-margins')
Have you considered to use
fig.update_layout(
autosize=False,
width=800,
height=800,)
and eventually reduce the size of your marker?
UPDATE
Full Code
import plotly.graph_objs as go
trace1 = go.Scatter(
x=x1_tsne, # x-coordinates of trace
y=y1_tsne, # y-coordinates of trace
mode='markers +text ', # scatter mode (more in UG section 1)
text = label3,
opacity = 1,
textposition='top center',
marker = dict(size = 12, color = color_4, symbol = marker_list_2, line=dict(width=0.5)),
textfont=dict(
color='black',
size=18, #can change the size of font here
family='Times New Roman'
)
)
data = [trace1]
layout = go.Layout(
autosize=False,
width=1000,
height=1000,
xaxis= go.layout.XAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
yaxis= go.layout.YAxis(linecolor = 'black',
linewidth = 1,
mirror = True),
margin=go.layout.Margin(
l=50,
r=50,
b=100,
t=100,
pad = 4
)
)
fig = go.Figure(data=data, layout=layout)

Dash+Plotly Synchronize zoom and pan between two plots using imshow

I try to synchronize zoom and pan between two graphs in a dashboard (dash + plotly). I obtain strange behavior when I zoom on a graph, the second graph does not update. I need to zoom on the second graph to make both graphs update but not with the same zoom nor the same location on the graphs. Furthermore the shapes of the two graphs change.
Below is the code I am in. I do not see I am doing wrong.
import os
from dash import Dash, html, dcc, Input, Output, State
import plotly.express as px
import numpy as np
import rasterio as rio
app2 = Dash(__name__)
data_folder = r'.\data'
store = {}
for filename in os.listdir(data_folder):
if os.path.isfile(os.path.join(data_folder, filename)):
band_name = filename.replace('.', '_').split(sep='_')[-2]
with rio.open(os.path.join(data_folder, filename)) as dataset:
nb_band = dataset.count
if nb_band == 1:
data = dataset.read(1)
else:
data = dataset.read(tuple(range(1, nb_band + 1)))
if band_name == 'triband':
data = np.swapaxes(data, 2, 0)
data = np.swapaxes(data, 0, 1)
store[band_name] = data.astype(float)
else:
store[f'B{band_name}'] = data.astype(float)
fig1 = px.imshow(store['triband'])
fig1.update_xaxes(showticklabels=False, showgrid=False, zeroline=False)
fig1.update_yaxes(showticklabels=False, showgrid=False, zeroline=False)
fig1.update_layout(
margin=dict(l=0, r=0, t=0, b=0),
plot_bgcolor='rgba(0, 0, 0, 0)',
paper_bgcolor='rgba(0, 0, 0, 0)',
)
# Application structure and content
app2.layout = html.Div(className='main', children=[
html.H1(children='Hello Dash', style={'padding': 10}),
html.Div(children=[
html.Div(children=[
dcc.Graph(
id='graph1',
figure=fig1,
responsive=True
)
], style={'padding': 5, 'flex': 1}),
html.Div(children=[
dcc.Graph(
id='graph2',
figure=fig1,
responsive=True
)
], style={'padding': 5, 'flex': 1})
], style={'display': 'flex', 'flex-direction': 'row'}),
])
#app2.callback(Output('graph2', 'figure'),
Input('graph1', 'relayoutData'),
State('graph2', 'figure'))
def graph_event1(select_data, fig):
if select_data is not None:
try:
fig['layout']['xaxis']['range'] = [select_data['xaxis.range[0]'], select_data['xaxis.range[1]']],
fig['layout']['yaxis']['range'] = [select_data['yaxis.range[0]'], select_data['yaxis.range[1]']]
except KeyError:
pass
return fig
#app2.callback(Output('graph1', 'figure'),
Input('graph2', 'relayoutData'),
State('graph1', 'figure'))
def graph_event2(select_data, fig):
if select_data is not None:
try:
fig['layout']['xaxis']['range'] = [select_data['xaxis.range[0]'], select_data['xaxis.range[1]']],
fig['layout']['yaxis']['range'] = [select_data['yaxis.range[0]'], select_data['yaxis.range[1]']]
except KeyError:
pass
return fig
if __name__ == '__main__':
app2.run_server(debug=True)
I found a solution : rather than creating two graphs, I created a graph with several subplots and force zoom and pan between subplots.
fig = make_subplots(rows=1, cols=3, shared_xaxes=True, shared_yaxes=True)
fig.add_trace(
px.imshow(store['triband']).data[0],
row=1, col=1
)
fig.add_trace(
px.imshow(index_store['NDVI']).data[0],
row=1, col=2
)
fig.add_trace(
px.imshow(np.where(index_store['NDVI'] >= np.median(index_store['NDVI']),
0.8 * np.max(index_store['NDVI']),
0.8 * np.min(index_store['NDVI']))
).data[0],
row=1, col=3
)
fig.update_xaxes(matches='x', showticklabels=False, showgrid=False, zeroline=False)
fig.update_yaxes(matches='y', showticklabels=False, showgrid=False, zeroline=False)

Display logos on Plot.ly Bar figure

I am currently doing a dataviz project, and I wish to add small images above each bar of my bar chart. For some reason, when I upload my own .png files, they can not be displayed.
When I use the .png files from the plot.ly documentation, it works fine. I produce it with the following:
new = go.Figure(data=[
go.Bar(name = 'DC Men',
x = dc_most_men.name,
y = dc_most_men.appearances,
marker_color ='rgb(244,188,60)'),
go.Bar(name = 'DC Females',
x = dc_most_females.name,
y = dc_most_females.appearances,
marker_color ='rgb(28,140,140)')
])
new.update_layout(
xaxis=dict(
showline=True,
showgrid=False,
showticklabels=True,
linecolor='rgb(204, 204, 204)',
linewidth=2,
ticks='outside',
tickfont=dict(
family='Arial',
size=12,
color='rgb(82, 82, 82)',
),
),
yaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
showticklabels=True,
),
autosize=False,
margin=dict(
autoexpand=False,
l=100,
r=20,
t=110,
),
showlegend=False,
plot_bgcolor='white'
)
new.add_layout_image(
dict(
source='https://github.itu.dk/storage/user/2360/files/eeb40480-9c3b-11ea-99e6-b9ae4b500657',
x=0.07,
y=1,
))
new.add_layout_image(
dict(
source="https://raw.githubusercontent.com/michaelbabyn/plot_data/master/benzene.png",
x=0.17,
y=0.8,
))
new.add_layout_image(
dict(
source="https://raw.githubusercontent.com/michaelbabyn/plot_data/master/benzene.png",
x=0.275,
y=0.5,
))
new.update_layout_images(dict(
xref="paper",
yref="paper",
sizex=0.1,
sizey=0.1,
xanchor="right",
yanchor="bottom"
))
Which very nicely produces the following barchart:
However, when I upload my own files to GitHub, it seems to not display the logo at all. I made sure to change the path to the following link as well.
The link I use is: https://user-images.githubusercontent.com/47081217/82669721-3b97db00-9c3c-11ea-90f6-c525e647bc49.png
Is there anything I have over-looked?
I don't think that from github could open an external link. Have you tried to download the png on the same folder where your notebook/script is?
I thought that if the format on GitHub is not the normal format, maybe the PILLOW library can handle it.
from PIL import Image
img = Image.open('https://github.itu.dk/storage/user/2360/files/eeb40480-9c3b-11ea-99e6-b9ae4b500657')

How to prevent plotly chart title from becoming left aligned after figure updates?

I have a plot in my dash app that initially has a title that is centered above the plot. However, once I update the figure the title becomes left aligned. I cannot figure out why this is the case and would like to know how I can prevent the title from shifting itself and instead keep in centered above the plot. Here is the code for my dash app:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objs as go
from nba_api.stats.static import players
from nba_api.stats.endpoints.shotchartdetail import ShotChartDetail
court_shapes = []
outer_lines_shape = dict(
type='rect',
xref='x',
yref='y',
x0='-250',
y0='-47.5',
x1='250',
y1='422.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(outer_lines_shape)
hoop_shape = dict(
type='circle',
xref='x',
yref='y',
x0='7.5',
y0='7.5',
x1='-7.5',
y1='-7.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(hoop_shape)
backboard_shape = dict(
type='rect',
xref='x',
yref='y',
x0='-30',
y0='-7.5',
x1='30',
y1='-6.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
),
fillcolor='rgba(10, 10, 10, 1)'
)
court_shapes.append(backboard_shape)
outer_three_sec_shape = dict(
type='rect',
xref='x',
yref='y',
x0='-80',
y0='-47.5',
x1='80',
y1='143.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(outer_three_sec_shape)
inner_three_sec_shape = dict(
type='rect',
xref='x',
yref='y',
x0='-60',
y0='-47.5',
x1='60',
y1='143.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(inner_three_sec_shape)
left_line_shape = dict(
type='line',
xref='x',
yref='y',
x0='-220',
y0='-47.5',
x1='-220',
y1='92.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(left_line_shape)
right_line_shape = dict(
type='line',
xref='x',
yref='y',
x0='220',
y0='-47.5',
x1='220',
y1='92.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(right_line_shape)
three_point_arc_shape = dict(
type='path',
xref='x',
yref='y',
path='M -220 92.5 C -70 300, 70 300, 220 92.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(three_point_arc_shape)
center_circle_shape = dict(
type='circle',
xref='x',
yref='y',
x0='60',
y0='482.5',
x1='-60',
y1='362.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(center_circle_shape)
res_circle_shape = dict(
type='circle',
xref='x',
yref='y',
x0='20',
y0='442.5',
x1='-20',
y1='402.5',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(res_circle_shape)
free_throw_circle_shape = dict(
type='circle',
xref='x',
yref='y',
x0='60',
y0='200',
x1='-60',
y1='80',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1
)
)
court_shapes.append(free_throw_circle_shape)
res_area_shape = dict(
type='circle',
xref='x',
yref='y',
x0='40',
y0='40',
x1='-40',
y1='-40',
line=dict(
color='rgba(10, 10, 10, 1)',
width=1,
dash='dot'
)
)
court_shapes.append(res_area_shape)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Div([
dcc.Graph(
id='shot-graph',
figure={
'layout': go.Layout(
title="test",
shapes= court_shapes,
height=800,
width=1000,
xaxis= dict(
showgrid=False,
range=[-300, 300],
showticklabels=False,
zeroline=False
),
yaxis= dict(
showgrid=False,
range=[-100, 500],
showticklabels=False,
zeroline=False
)
)
},
config={
'displayModeBar': False
}
),
],style = {'margin': 'auto', 'width': '50%'}),
html.Div([
dcc.Input(id='playerName-state', type='text', value='Brook Lopez'),
dcc.Input(id='season-state', type='text', value='2018-19'),
html.Button('Submit', id='button')
],style = {'margin-left': '675px'})
])
#app.callback(
Output('shot-graph', 'figure'),
[Input('button', 'n_clicks')],
state=[
State(component_id='playerName-state', component_property='value'),
State(component_id='season-state', component_property='value')]
)
def update_figure(n_clicks, playerName, season):
playerID = players.find_players_by_full_name(str(playerName))[0]['id']
shotchart_detail = ShotChartDetail(team_id = 0, player_id = playerID, season_nullable= str(season), context_measure_simple= "FGA")
shotData = shotchart_detail.get_data_frames()[0]
shotData["LOC_X"] *= -1
made_shots = shotData.loc[shotData.SHOT_MADE_FLAG == 1]
missed_shots = shotData.loc[shotData.SHOT_MADE_FLAG == 0]
fig = go.Figure()
fig.add_trace(go.Scatter(x=made_shots["LOC_X"], y=made_shots["LOC_Y"], mode='markers', marker_color="BLUE", name="Made Shot"))
fig.add_trace(go.Scatter(x=missed_shots["LOC_X"], y=missed_shots["LOC_Y"], mode='markers', marker_color="RED", name="Missed Shot"))
layout = go.Layout(
title='Shots by %s in the %s NBA season' % (playerName, season),
showlegend=False,
xaxis=dict(
showgrid=False,
range=[-300, 300],
showticklabels=False,
zeroline=False
),
yaxis=dict(
showgrid=False,
range=[-100, 500],
showticklabels=False,
zeroline=False
),
height = 800,
width = 1000,
shapes=court_shapes,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)'
)
fig.update(layout=layout)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
The reason the title is becoming left-aligned (and various other style changes are likely occurring!) is that while your initial figure is defined as straight dict objects, your callback returns a go.Figure object which uses Plotly's new built-in template.
To make go.Figure not do this, you can pass in template=None to your go.Layout constructor.
More documentation here: https://plot.ly/python/templates/

Plotly legend next to each subplot, Python

After noticing that there was no answer to this question at the moment, I would like to know if anyone has an idea how to:
Have a legends for each subplot.
Group legends by name. (Ex: for different subplots, all have the same two curves but with different values).
Here's my Plotly script:
from plotly import tools
import plotly.plotly as py
import plotly.graph_objs as go
import plotly
nom_plot=[]
trace1 = go.Scatter(x=[1, 2, 3], y=[4, 5, 6],name='1',showlegend=True)
nom_plot.append('GRAPH 1')
trace2 = go.Scatter(x=[20, 30, 40], y=[50, 60, 70],name='2',yaxis='y2')
nom_plot.append('GRAPH 2')
trace3 = go.Scatter(x=[300, 400, 500], y=[600, 700, 800],showlegend=False)
nom_plot.append('GRAPH 3')
trace4 = go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000])
nom_plot.append('GRAPH 4')
trace5 = go.Scatter(x=[20, 30, 40], y=[50, 60, 70])
nom_plot.append('GRAPH 5')
print(trace1)
fig = tools.make_subplots(rows=4, cols=2, subplot_titles=(nom_plot))
fig.append_trace(trace1, 1, 1)
fig['layout']['xaxis1'].update(title='xaxis 1 title')
fig.append_trace(trace2, 1, 1)
fig.append_trace(trace3, 2, 1)
fig.append_trace(trace4, 2, 2)
fig['layout']['yaxis3'].update(title='yaxis 3 title')
fig.append_trace(trace5, 3, 1)
fig['layout']['yaxis2'].update(
overlaying='y1',
side='right',
anchor='x1',
# domain=[0.15, 1],
range=[2, 6],
# zeroline=False,
showline=True,
showgrid=False,
title='yaxis 3 title'
)
fig['layout'].update(height=1000, width=1000, title='Multiple Subplots' +' with Titles')
plotly.offline.plot(fig, filename='multiple-y-subplots6.html')
This what I obtain (Using Plotly Script above):
And this is what I want (Made by Pygal):
The solution is to create an HTML file that merge sevral charts offline rendered as html files:
import plotly
import plotly.offline as py
import plotly.graph_objs as go
fichier_html_graphs=open("DASHBOARD.html",'w')
fichier_html_graphs.write("<html><head></head><body>"+"\n")
i=0
while 1:
if i<=40:
i=i+1
#______________________________--Plotly--______________________________________
color1 = '#00bfff'
color2 = '#ff4000'
trace1 = go.Bar(
x = ['2017-09-25','2017-09-26','2017-09-27','2017-09-28','2017-09-29','2017-09-30','2017-10-01'],
y = [25,100,20,7,38,170,200],
name='Debit',
marker=dict(
color=color1
)
)
trace2 = go.Scatter(
x=['2017-09-25','2017-09-26','2017-09-27','2017-09-28','2017-09-29','2017-09-30','2017-10-01'],
y = [3,50,20,7,38,60,100],
name='Taux',
yaxis='y2'
)
data = [trace1, trace2]
layout = go.Layout(
title= ('Chart Number: '+str(i)),
titlefont=dict(
family='Courier New, monospace',
size=15,
color='#7f7f7f'
),
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
yaxis=dict(
title='Bandwidth Mbit/s',
titlefont=dict(
color=color1
),
tickfont=dict(
color=color1
)
),
yaxis2=dict(
title='Ratio %',
overlaying='y',
side='right',
titlefont=dict(
color=color2
),
tickfont=dict(
color=color2
)
)
)
fig = go.Figure(data=data, layout=layout)
plotly.offline.plot(fig, filename='Chart_'+str(i)+'.html',auto_open=False)
fichier_html_graphs.write(" <object data=\""+'Chart_'+str(i)+'.html'+"\" width=\"650\" height=\"500\"></object>"+"\n")
else:
break
fichier_html_graphs.write("</body></html>")
print("CHECK YOUR DASHBOARD.html In the current directory")
Result:
I used two side by side Div elements to emulate Plotly subplot. Doing this way, we have independent legends. However, if we want to share an axis, we should do it manually:
app.layout = html.Div(children=[
html.Div(['YOUR FIRST GRAPH OBJECT'],
style = {'float':'left', 'width':'49%'}) ,
html.Div(['YOUR SECOND GRAPH OBJECT'],
style = {'float':'right', 'width':'49%'})
])

Categories