Streamlit `altair_chart` chart not interactive - visualization

I am trying to plot an interactive financial chart, but it doesn’t turn dynamic when I use st.altair_chart (as is the default for altair charts). Here’s the code:
base = alt.Chart(df).encode(
alt.X('Date:T', axis=alt.Axis(labelAngle=-45)),
color=alt.condition("datum.Open <= datum.Close",
alt.value("#06982d"), alt.value("#ae1325"))
)
rule = base.mark_rule().encode(alt.Y('Low:Q', title='Price',
scale=alt.Scale(zero=False)), alt.Y2('High:Q'))
bar = base.mark_bar().encode(alt.Y('Open:Q'), alt.Y2('Close:Q'))
st.altair_chart(rule + bar, use_container_width=True)
This code results in the plot as follows:
(For reference,the original question)

Basically, you have to explicitly layer the markings and call on .interactive() to make the axis interactive:
base = alt.Chart(df).encode(
alt.X('Date:T', axis=alt.Axis(labelAngle=-45)),
color=alt.condition("datum.Open <= datum.Close",
alt.value("#06982d"), alt.value("#ae1325"))
)
chart = alt.layer(
base.mark_rule().encode(alt.Y('Low:Q', title='Price',
scale=alt.Scale(zero=False)), alt.Y2('High:Q')),
base.mark_bar().encode(alt.Y('Open:Q'), alt.Y2('Close:Q')),
).interactive()
st.altair_chart(chart, use_container_width=True)

Related

plotly go Scattermapbox is not showing markers

I some how have encountered some odd bug. When i try to create a Scattermapbox the markers dont render. This bug came out of no where, It was working perfectly fine then my internet went out and now for the last 8 hours it has not been working.
Ive tried running it in different IDE's
running it in google colab to make sure its not my machine
different data sets.
i am unsure what i have done wrong
The tooltips do display however when i hover over the invisible points.
and if use the export to png button everything is shown.
but no matter what it wont show up on the actual map itself and i am at my wits end.
I will include the callback function bellow.
#app.callback(
Output('2dmap','figure'),
[Input('2dgraph', 'clickData'),
Input('checklist', 'value')])
def update_map_2d(clickData,checklist):
# =============================================================================
# P1. Render Map when no point is clicked
# =============================================================================
# If No point has been clicked
if clickData is None:
#make a map
maps2d = go.Figure(go.Scattermapbox(
lat=[], # set lat and long
lon=[],
mode='markers',
marker =({'size':5.5}) # make markers size variable
))
# set up map layout
maps2d.update_layout(
autosize=True, # Autosize
hovermode='closest', # Show info on the closest marker
showlegend=True, # show legend of colors
mapbox=dict(
accesstoken=mapbox_access_token, # token
bearing=0, # starting facing direction
# starting location
center=dict(
lat=td.cLat,
lon=td.cLong
),
#angle and zoom
pitch=0,
zoom=12
),
#height and width
width=1000,
height=1000
)
return maps2d
else:
xCoord = int(clickData['points'][0]['x'])
yCoord = int(clickData['points'][0]["y"])
solutionRow = preatoFrontier.loc[(preatoFrontier['x'] == xCoord)&(preatoFrontier['y'] == yCoord)]
solId = int(solutionRow['SolId'])
#solId = 49
solution = td.getSolution(solutions, solId)
color = []
for row in solution['upGrade']:
if row == 0:
color.append('grey')
if row == 1:
color.append('green')
if row == 2:
color.append('blue')
if row == 3:
color.append('red')
solution['color'] = color
solution2 = solution[solution['color'].isin(checklist)]
maps2d = go.Figure(go.Scattermapbox(
lat=solution2['lat'],
lon=solution2['long'],
mode='markers',
#marker =({'color':solution['color']},{'size':5.5})
marker=dict(
size=12,
color=solution2['color'], #set color equal to a variable
colorscale='Viridis', # one of plotly colorscales
showscale=True
)
))
#=============================================================================
# P3. Map Layout
#=============================================================================
#set up map layout
maps2d.update_layout(
autosize=False, # Autosize
hovermode='closest', # Show info on the closest marker
showlegend=True, # show legend of colors
mapbox=dict(
accesstoken=mapbox_access_token, # token
bearing=0, # starting facing direction
# starting location
center=dict(
lat=td.cLat,
lon=td.cLong
),
#angle and zoom
pitch=0,
zoom=10
),
#height and width
width=1000,
height=1000
)
return maps2d
After a lot of hair pulling, i thought to try creating a new venv and uploading packages one by one and running to see how and where it fails. The last package i installed before it broke was dash-tools and sure enough some how that was causing mapbox to bug out hard. So dont install dash-tools

Document generator, different margins for certain pages

I am creating a document using MATLAB's mlreportgen.dom.*;
I would like to be able to set the first and last page of a document to have no margins. This way I can get images to fit right across the page.
I am having difficulties with this, see example code
import mlreportgen.dom.*;
d = Document('myreport', 'pdf');
open(d);
currentLayout = d.CurrentPageLayout;
pdfheader = PDFPageHeader();
p = Paragraph('Sample Traffic Data in Austin');
p.Style = [p.Style, {HAlign('left'), Bold(true), FontSize('12pt')}];
append(pdfheader, p);
currentLayout.PageHeaders = pdfheader;
currentLayout.PageMargins.Gutter = '0.0in';
currentLayout.PageMargins.Left = '0.0in';
currentLayout.PageMargins.Right = '0.0in';
close(d);
rptview(d.OutputPath);
So far, I have naively tried to add a page break and redefine margins with no success. It appears to use the margins that come last in the document.

How to keep selected data persistent through callback in Dash/Plotly's clustered bar chart

I'm using Dash to plot some data. I currently have a clustered bar chart with two data sets (one for each bar in the clusters.) These data sets have their name and the corresponding color of the bars displayed in the top, left-hand corner of the figure. They can be clicked to be toggled on and off, which will remove their corresponding bars from the chart.
Separately, I have a checklist of items that can be displayed in the chart. I am using a callback to update the graph so that it only displays what the user has checked. This updates the graph as expected, however, it also resets the bars/datasets such that both are enabled. Ie. if you select only one of the bars, then select some new checklist items, it will display the new checklist items and both of the bars.
My thinking is that the logical way to do this is to pass some variable as a second input to the callback function, then set up the outputted figure within the function to only display the proper bars. However, I can't seem to find a variable that contains this data.
From what I can tell, the accessible properties of the Plotly graph object are 'id', 'clickData', 'clickAnnotationData', 'hoverData', 'clear_on_unhover', 'selectedData', 'relayoutData', 'figure', 'style', 'className', 'animate', 'animation_options', 'config', and 'loading_state'.
I've investigated all of these, and it seems that none hold the data that I am looking for. Does anyone know of an easy way to access this data?
This is how my callback is working right now:
#app.callback(
dash.dependencies.Output('theGraph', 'figure'),
[dash.dependencies.Input('theChecklist','values'),
dash.dependencies.Input('theGraph', 'clickData')
]
)
def updateGraph(checklistValues, figureInput):
#print to see what the variables hold
print(checklistValues)
print(figureInput)
figure=go.Figure(
data = [
go.Bar(
x = df[df['MyColumnName'].isin(checklistValues)].groupby('MyColumnName').size().index,
y = df[df['MyColumnName'].isin(checklistValues)].groupby('MyColumnName').size().values,
name = 'Bar 1'
),
go.Bar(
x = df[df['MyColumnName'].isin(checklistValues)].groupby('MyColumnName')['# cores'].sum().reset_index()['MyColumnName'],
y = df[df['MyColumnName'].isin(checklistValues)].groupby('MyColumnName')['# cores'].sum().reset_index()['MyOtherColumnName'],
name = 'Bar 2'
)
],
layout=go.Layout(
title='The Title',
showlegend=True,
legend=go.layout.Legend(
x=0,
y=1.0
),
margin=go.layout.Margin(l=40, r=40, t=40, b=110)
)
)
return figure

SSRS: Custom colors for the Category axis of a stacked bar chart

I have a stacked bar chart that only ever has 5 categories(but the value of the categories change from year to year, it is a sliding 5 year window).
I have successful customised the bars to the colors I want.
But now I wish to make the label of each Category the same color as the customised bar color.
Is there a way to do this?
You can use custom code for this.
In Report Properties | Code, you can paste in the following code:
Private colourPalette As String() = {"#418CF0", "#FCB441", "#DF3A02", "#056492", "#BFBFBF", "#1A3B69", "#FFE382", "#129CDD", "#CA6B4B", "#005CDB", "#F3D288", "#506381", "#F1B9A8", "#E0830A", "#7893BE"}
Private count As Integer = 0
Private mapping As New System.Collections.Hashtable()
Public Function GetColour(ByVal groupingValue As String) As String
If mapping.ContainsKey(groupingValue) Then
Return mapping(groupingValue)
End If
Dim c As String = colourPalette(count Mod colourPalette.Length)
count = count + 1
mapping.Add(groupingValue, c)
Return c
End Function
This will give you the option of the pastel colour palette. If you want other colours, simply replace the hex colour codes with values of your choice.
To use this, simply use the following expression:
=Code.GetColour(Fields!Thingy.Value)
Use this on your series and your label fill expressions. This will ensure that the same colour appears for both. If you have multiple graphs with the same values in, this will also ensure that the same data series across multiple graphs always have the same colour.

Is there a limit to the amount of data you can put in a MATLAB pie/pie3 chart?

I have everything going swimmingly on my pie chart and 3D pie charts within MATLAB for a dataset, however, I noticed that even though I have 21 pieces of data for this pie-chart being fed into the pie-chart call, only 17 appear.
PieChartNums = [ Facebook_count, Google_count, YouTube_count, ThePirateBay_count, StackOverflow_count, SourceForge_count, PythonOrg_count, Reddit_count, KUmail_count, Imgur_count, WOWhead_count, BattleNet_count, Gmail_count, Wired_count, Amazon_count, Twitter_count, IMDB_count, SoundCloud_count, LinkedIn_count, APOD_count, PhysOrg_count];
labels = {'Facebook','Google','YouTube','ThePirateBay','StackOverflow', 'SourceForge', 'Python.org', 'Reddit', 'KU-Email', 'Imgur', 'WOWhead', 'BattleNet', 'Gmail', 'Wired', 'Amazon', 'Twitter', 'IMDB', 'SoundCloud', 'LinkedIn', 'APOD', 'PhysOrg'};
pie3(PieChartNums)
legend(labels,'Location','eastoutside','Orientation','vertical')
This goes for the labels and the physical graph itself.
Excuse the poor formatting in terms of the percentage cluster, this is just a rough version. I tried every orientation and even splitting labels between the orientations without any luck.
Quasi-better resolution for Pie Chart -- Imgur Link
Like Daniel said - it appears that there simply isn't any non-negative data for the missing slices. I tried reproducing your problem with the following initialization, yet it resulted in normal-looking chart:
[ Facebook_count, Google_count, YouTube_count, ThePirateBay_count, ...
StackOverflow_count, SourceForge_count, PythonOrg_count, Reddit_count, ...
KUmail_count, Imgur_count, WOWhead_count, BattleNet_count, Gmail_count, ...
Wired_count, Amazon_count, Twitter_count, IMDB_count, SoundCloud_count, ...
LinkedIn_count, APOD_count, PhysOrg_count] = deal(0.04);
In order to verify this hypothesis - could you provide the data you're using for the chart? Do you get any warnings when plotting the chart?
From inside the code of pie.m:
if any(nonpositive)
warning(message('MATLAB:pie:NonPositiveData'));
x(nonpositive) = [];
end
and:
for i=1:length(x)
if x(i)<.01,
txtlabels{i} = '< 1%';
else
txtlabels{i} = sprintf('%d%%',round(x(i)*100));
end
end
You can see that MATLAB doesn't delete valid slices, but only renames them if the data values are small.