Plotly Text Annotation shows the same text throughout - python

I am trying to show the text on the bars based on some filtered data but the text shows the same value for the last item in the list. I can't seem to find out what the issue is because display_texts itself gives me what I expect
filtered_data = df[df["Year"] == 2017]
display_texts = filtered_data["column_name"].tolist()
fig = px.bar(
filtered_data,
x="x_column",
y="y_column",
color="color",
title="some title",
)
fig.update_traces(
texttemplate=display_texts,
textposition="outside",
)
fig.update_layout(showlegend=False)
fig.update_layout(autosize=False, width=1800, height=600)

You should remove texttemplate=display_texts and add text=display_texts to px.bar.

Related

Define title to a matplotlib table

I have a table generated by matplotlib, and I want to insert a title for it. Do anyone know how to do it?
ax = fig.add_subplot(111)
fig = plt.figure(constrained_layout=True)
spec2 = gridspec.GridSpec(ncols=2, nrows=3, figure=fig )
ax1 = fig.add_subplot(spec2[0, 0])
ax2 = fig.add_subplot(spec2[0, 1])
ax1.axis('off')
ax2.axis('off')
table_data=[
["Ni_Tot ", "NN", "2.5%" , round(df.NN_Ni_Tot.quantile(0.025),3)],
["N. of Samples", count, "5%" , round(df.NN_Ni_Tot.quantile(0.05),3)],
["Minimum", round(min(df['NN_Ni_Tot'].apply(pd.to_numeric)),3), "25%" , round(df.NN_Ni_Tot.quantile(0.25),3)],
["Maximum", round(max(df['NN_Ni_Tot'].apply(pd.to_numeric)),3), "Median", round(df.NN_Ni_Tot.quantile(0.5),3)],
["Average", round(statistics.mean(df['NN_Ni_Tot'].apply(pd.to_numeric)),3),"75%", round(df.NN_Ni_Tot.quantile(0.75),3)],
["Variance", round(df['NN_Ni_Tot'].var(),2), "95%", round(df.NN_Ni_Tot.quantile(0.95),3)],
["Std Deviation", round(df['NN_Ni_Tot'].std(),2),"97.5%", round(df.NN_Ni_Tot.quantile(0.975),3)],]
table = ax1.table(cellText=table_data, loc='center', cellLoc='center')
table.set_fontsize(14)
table.scale(1.5,1.4)
https://i.stack.imgur.com/P27Vu.png
ax.set_title("Your title")
Relevant documentation
ax1.set_title("Your title")
The code line above worked, but the title was positioned in the middle of the table, overlapping the data. So I had to ajust it manually
ax1.set_title("NN_NI", fontsize=8, y=1.8, pad=-14)

How to show only one trace when plotly updatemenus load on Jupyter Notebook?

I have two graphs that I want to show using plotly's updatemenus feature. I am able to populate and display the data using the updatemenus feature. However, when the plot loads, both the graphs are displayed initially. Is there a way to show only one graph when the plot loads initially?
I went through the documentation for updatemenus on plotly but could not find any attribute that will help me in achieving this.
trace28 = go.Bar(x=for1.head()['Name'],
y=for1.head()['G'],
name='Goals',
opacity=0.8
)
trace29 = go.Bar(x=for1.head()['Name'],
y=for1.head()['A'],
name='Assists',
opacity=0.8
)
trace30 = go.Bar(x=for2.head()['Name'],
y=for2.head()['G'],
name='Goals',
opacity=0.8
)
trace31 = go.Bar(x=for2.head()['Name'],
y=for2.head()['A'],
name='Assists',
opacity=0.8
)
updatemenus = list([dict(active=-1,
type='buttons',
buttons=list([dict(label='2011/12',
method='update',
args=[dict(visible=[True, True, False, False]),
dict(title='<b>Forward Stats 2011/12</b>')
]
),
dict(label='2012/13',
method='update',
args=[{'visible':[False, False, True, True]},
{'title':'<b>Forward Stats 2012/13</b>'}
]
),
])
),
])
layout = go.Layout(title='<b>Forward Stats</b>',
xaxis=dict(title='<b><i>Player Name</b></i>'),
yaxis=dict(title='<b><i>Goals/Assists</b></i>'),
updatemenus=updatemenus,
showlegend=False,
barmode='group'
)
data = [trace28, trace29, trace30, trace31]
fig = go.Figure(data=data, layout=layout)
py.iplot(fig)
I want to display only trace28 and trace29 when the plot loads. Right now, all the traces are being shown when the plot loads.
While making the trace, you can set visible = "legendonly". Then you can toggle the trace by clicking on the line in the legend. Does that do what you want?
So you would change trace30 and trace31
trace30 = go.Bar(x=for2.head()['Name'],
y=for2.head()['G'],
name='Goals',
opacity=0.8,
visible = "legendonly"
)
trace31 = go.Bar(x=for2.head()['Name'],
y=for2.head()['A'],
name='Assists',
opacity=0.8,
visible = "legendonly"
)
Does that get you your desired functionality?

Plot two different datasets into plotly using drop down menu

I have two different datasets (x0,y0), (x1,y1). I need to create two plots and use a drop down menu to select between them.
I am using this code:
import plotly
import plotly.graph_objs as go
import random
x0 = [x for x in range(0,20)]
x1 = [x for x in range(5,100)]
y0 = [random.randint(0,20) for x in range(len(x0))]
y1 = [random.randint(0,50) for x in range(len(x1))]
trace1 = go.Scatter(x=x0,y=y0,line=dict(shape='vh'))
trace2 = go.Scatter(x=x1,y=y1,line=dict(shape='vh'))
data = [trace1,trace2]
updatemenus = list([
dict(active=0,
buttons=list([
dict(label = "4 Aug 1",
method = "update",
args= [data[0]]),
dict(label = "4 Aug 2",
method = "update",
args= [data[1]])]))])
layout = dict(title="Dropdown",
showlegend=True,
xaxis=dict(title="Hours"),
yaxis=dict(title="Number"),
updatemenus=updatemenus)
fig=dict(data=data, layout=layout)
plotly.offline.plot(fig)
Using this code, it plots two datasets into one area, which I would not like to do. And when I select a proper chart on dropdown menu, it just fails to load proper chart.
The problem is that you're directly assigning traces to args. Instead, you should be using the visible property to control which traces in data are visible:
updatemenus = list([
dict(active=0,
showactive = True,
buttons=list([
dict(label = "4 Aug 1",
method = "update",
args = [{"visible": [True, False]}]), # hide trace2
dict(label = "4 Aug 2",
method = "update",
args = [{"visible": [False, True]}]) # hide trace1
]))])
If you only want to show the first trace when the page is loaded, you also need to explicitly set the visible attribute of the second trace to False:
trace1 = go.Scatter(x=x0,y=y0,line=dict(shape='vh'))
trace2 = go.Scatter(x=x1,y=y1,line=dict(shape='vh'), visible=False)
data = [trace1,trace2]
See the official Plotly example.

Python Plotly: Using dropdown menu to switch between choropleth map and scatterplot

I am new to using plotly and I am attempting to build a dynamic visualisation using python and plotly. I hope to be able to switch between a world choropleth map and a scatter plot using a drop-down menu.
So far I have been able to successfully get a dropdown menu to appear and show the required labels and even show a single plot by removing either the choropleth map or scatter plot trace from the data variable. The problem is that I when I try to have both plots implemented the choropleth map is drawn over the top of the scatterplot regardless of the menu option I choose.
A screenshot of the output.
Areas I Have Looked For A Solution
The plotly reference and looked through the updatemenus and layout sections among many others.
Reviewed the ploty python tutorial page for dropdowns and implementing parts of the suggestion in my code with a focus on the update method.
I have found a StackOverflow page that seemed to be very close to the answer I needed however not quite.
Finally, I also searched the plotly community forum.
The Code
Note I have removed a portion of the code such as imports and data at the beginning.
scatterplot = go.Scatter(
y = df2['Renewable energy consumption (% of total final energy consumption) 2015'],
x = df2['GDP per capita, PPP (constant 2011 international $) 2015'],
mode='markers',
ids=df2['Country Name'],
showlegend = False,
marker = dict(
size = 8,
color = np.random.randn(500),
),
textfont = dict(
size = 14,
color = 'black')
)
choropleth_map = dict(
type = 'choropleth',
locations = df['ISO3166_alpha3'],
z = df['renewables_mtoe'],
text = df['Country'],
colorscale = [[0,"rgb(106, 240, 255)"],[0.10,"rgb(106, 199, 255)"],[0.70,"rgb(50, 100, 255)"],[0.93,"rgb(0, 43, 198)"],\
[0.99999,"rgb(0, 24, 109)"],[1,"rgb(220, 220, 220)"]],
autocolorscale = False,
reversescale = True,
marker = dict(
line = dict (
color = 'rgb(180,180,180)',
width = 0.5
) ),
colorbar = dict(
title = 'mtoe<br>',
tickfont = dict(
size = 16),
titlefont = dict(
size = 16)),
)
data = [choropleth_map, scatterplot]
updatemenus = list([
dict(active=0,
buttons=list([
dict(label = 'choropleth_map',
method = 'update',
args = [{'visible': [True,False]},
{'title': 'The Map'}]),
dict(label = 'scatterplot',
method = 'update',
args = [{'visible': [False,True]},
{'title': 'Scatterplot'}]),
]),
)
])
layout = dict(title='default', showlegend=False,
updatemenus=updatemenus,
geo = dict(showframe = True,
showcoastlines = False,
showland = True,
landcolor = '#dcdcdc',
projection = dict(type = 'natural earth'))
)
fig = dict( data=data, layout=layout )
plotly.offline.iplot(fig, validate=True)
A big thank you in advance to anyone who can help. I have spent days trying to solve this problem, it has even driven me to make my first post on StackOverflow.

Python Bokeh graph displays two lines when update function called

I've been working with the python bokeh function, and I wish to display a graph of a stock when the ticker is entered into the TextInput section. However, in my case the only way I've made this work is to create a new p.line within the update function, which overlays one stock graph on top of another. Is there a way to update my source data or update function such that a graph with only the input stock is shown?
p=figure(
height=400,
x_axis_type='datetime',
title=(company+' ('+tickerstring+') '),
tools='pan, box_zoom, wheel_zoom, reset',
)
p.line('x', 'y', source=source)
line1=p.line(thedates, stockcloseprices)
p.grid.grid_line_color="white"
p.xaxis.axis_label = 'Date'
p.yaxis.axis_label = 'Price'
p.add_tools(HoverTool(
tooltips=[
("Date", "#x{%F}"),
('Close',"#y")
],
formatters={
'x':'datetime', # use 'datetime' formatter for 'date' field
},
mode='vline'
))
source = ColumnDataSource(data=dict(
x=thedates,
y=stockcloseprices
))
div = Div(text='<br><b> Key Points </b><br><br>'+percentagechange+'<br><br>'+performance,
width=200, height=100)
def update(f):
fstocksymbol=str(f.upper())
if fstocksymbol in stocksymbols:
p.title.text = (symbolsdictionary[fstocksymbol]).upper()+' ('+fstocksymbol+')'
tickerstring=fstocksymbol
firstfunction=stockname(tickerstring)
secondfunction=stockdata(firstfunction)
stockdates=[]
stockcloseprices=[]
for value in secondfunction:
stockdates.append(value[0])
stockcloseprices.append(value[4])
thedates = np.array(stockdates, dtype=np.datetime64)
p.line(thedates, stockcloseprices)
push_notebook()
elif fstocksymbol=='':
print('')
else:
print("")
interact(update, f='')
grid = gridplot([p, div, button], ncols=2, plot_width=570, plot_height=400)
show(grid, notebook_handle=True)
There are several example notebooks that show how to update a data source for an existing glyph in the examples directory on GitHub:
https://github.com/bokeh/bokeh/tree/master/examples/howto/notebook_comms
In brief, you want to update the data source:
source.data = new_data_dict
push_notebook()

Categories

Resources